Reputation: 533
i've got started studying Flutter. I'm trying to using MethodChannel and MethodCall to communicate with Android platform. I don't know how to pass arguments to the Android code.
Below is my code.
// dart
void _onClick() async {
var parameters = {'image':'starry night'};
await platform.invokeMethod('showToast', new Map.from(parameters));
}
// kotlin
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
Log.d("MainActivity", ">> ${call.method}, ${call.arguments}")
when (call.method) {
"showToast" -> {
showToast("toast")
}
else -> {
Log.d("MainActivity", "fail");
}
}
I can check an arguement value what I passed by log message what I printed.
{image=starry night}
But I don't know how to parse to a map object.
Upvotes: 22
Views: 14965
Reputation: 268024
Dart side (sending data)
var channel = MethodChannel('foo_channel');
var dataToPass = <String, dynamic>{
'os': 'Android',
};
await channel.invokeListMethod<String>('methodInJava', dataToPass);
Java side (receiving data):
if (methodCall.method.equals("methodInJava")) {
// Get the entire Map.
HashMap<String, Object> map = (HashMap<String, Object>) methodCall.arguments;
Log.i("MyTag", "map = " + map); // {os=Android}
// Or get a specific value.
String value = methodCall.argument("os");
Log.i("MyTag", value); // Android
}
Upvotes: 6
Reputation: 512186
On the Flutter side, you can pass arguments by including them as a map in the invokeMethod
call.
_channel.invokeMethod('showToast', {'text': 'hello world'});
On the Kotlin side you can get the parameters by casting call.arguments
as a Map or getting a particular argument from call.argument()
.
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"showToast" -> {
val text = call.argument<String>("text") // hello world
showToast(text)
}
}
}
Upvotes: 31