Skip to content

Instantly share code, notes, and snippets.

@devtronic
Created October 19, 2019 21:45
Show Gist options
  • Save devtronic/19095c22930b05b9c446520f1847a113 to your computer and use it in GitHub Desktop.
Save devtronic/19095c22930b05b9c446520f1847a113 to your computer and use it in GitHub Desktop.
Implementing Flutter PlatformChannels methods the smart way
package my.flutter.plugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import android.content.ContentValues.TAG
import android.util.Log
import java.lang.reflect.Method
import java.util.HashMap
class FlutterPlugin : MethodCallHandler {
// ...
// This method is getting called through a platform channel
fun getPlatformVersion(call: MethodCall, result: Result) {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
}
// region MethodCallHandler
// This map holds all available methods in this class
private val methodMap = HashMap<String, Method>()
// Handles the method call and calls the correct method in this class
override fun onMethodCall(call: MethodCall, result: Result) {
if (methodMap.isEmpty()) {
fetchMethods()
}
val method = methodMap.get(call.method)
if (null == method) {
result.notImplemented()
return
}
Log.v(TAG, "Method: " + call.method)
val args = arrayOfNulls<Any>(2)
args[0] = call
args[1] = result
try {
method.invoke(this, *args)
} catch (e: Exception) {
result.error(call.method, e.message, e)
}
}
// Fetches all methods in this class
private fun fetchMethods() {
val c = this::class.java
val m = c.declaredMethods
for (method in m) {
methodMap[method.name] = method
}
}
// endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment