The guide you mentioned talk about platform channel and how to communicate (Flutter side and Android side).
In your case, to communicate between Flutter and Android, you need a MethodChannel
in both sides.
When creating a MethodChannel, you'll have to provide a unique name (usually, your package domain name) to let the engine create a channel between your Flutter side and your Android side.
Flutter side:
class MyPlugin {
static const _channel = MethodChannel("example.dev/plugin");
Future<String> getHelloWorld() async {
final message = await _channel.invokeMethod<String>("getHelloWorld");
print(message);
return message;
}
}
Android side (Kotlin):
class MyPlugin : FlutterPlugin, MethodCallHandler {
private lateinit var channel: MethodChannel
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(binding.binaryMessenger, "example.dev/plugin")
channel.setMethodCallHandler(this)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "getHelloWorld") {
result.success("Hello world!")
return
}
result.notImplemented()
}
}
onMethodCall
is called on Android side when you call invokeMethod
from Flutter side.
Note that you pass a string to invokeMethod
, it will be available in Android side in call.method
, as shown in above example.
When you need to pass additional arguments, you can do so with:
Flutter side:
// ...
int age = 42;
String message = "This is the way";
String answer = await _channel.invokeMethod<String>("getMessage", <String, Object>{
"age": age,
"message": message
});
print(answer);
// ...
Android side (Kotlin):
// ...
if (call.method == "getMessage") {
if (!call.hasArgument("age") || !call.hasArgument("message")) {
result.error("MissingArgumentError", "You must provide age and message parameters.", null)
return
}
val age: Int = call.argument<Int>("age")!!
val message: String = call.argument<String>("message")!!
result.success("$message at $age years old")
return
}
// ...
You can pass common types of data through a MethodChannel, see list of supported types.
Similarly, you can use an EventChannel
between both sides to emit events (aka Stream).
You'll find more details in the guide as it comes from the official documentation.