我已经开始学习 Flutter。我正在尝试使用 MethodChannel 和 MethodCall 与 Android 平台进行通信。我不知道如何将参数传递给 Android 代码。
下面是我的代码。
// 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");
}
}
我可以检查我通过打印的日志消息传递的争论值。
{image=starry night}
但我不知道如何解析为 map 对象。
最佳答案
flutter
在 Flutter 方面,您可以通过将参数作为映射包含在 invokeMethod
中来传递参数。称呼。
_channel.invokeMethod('showToast', {'text': 'hello world'});
Kotlin 在 Kotlin 方面,您可以通过强制转换
call.arguments
来获取参数。作为 Map 或从 call.argument()
获取特定参数.override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"showToast" -> {
val text = call.argument<String>("text") // hello world
showToast(text)
}
}
}
关于android - 如何将参数从 Flutter 传递给 Kotlin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49218395/