如何将Flutter的论点传递给Kotlin?

Kyo*_* Yi 5 android kotlin flutter

我已经开始学习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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以检查一个争论值,该值是我通过日志消息传递的内容,是我打印的内容。 {image=starry night} 但是我不知道如何解析到地图对象。

Sur*_*gch 20

在 Flutter 方面,您可以通过将参数作为映射包含在invokeMethod调用中来传递参数。

_channel.invokeMethod('showToast', {'text': 'hello world'});
Run Code Online (Sandbox Code Playgroud)

科特林

在 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)
    }   
  }
}
Run Code Online (Sandbox Code Playgroud)


Cop*_*oad 6

Dart端(发送数据)

var channel = MethodChannel('foo_channel');
var dataToPass = <String, dynamic>{
  'os': 'Android',
};
await channel.invokeListMethod<String>('methodInJava', dataToPass);
Run Code Online (Sandbox Code Playgroud)

Java端(接收数据):

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
}
Run Code Online (Sandbox Code Playgroud)