4

我在 Dart 和 Kotlin 中建立了一个基本的方法通道

飞镖代码


  Future<void> _updateProfile() async {
    try {
      var result = await platform.invokeMethod('updateProfile');
      print(result);
    } on PlatformException catch (e) {
      print('Failed to get battery level: ${e.message}');
    }

    setState(() {
//      print('Setting state');
    });
  }

Kotlin 代码

MethodChannel(flutterView, channel).setMethodCallHandler { call, result ->
      if(call.method == "updateProfile"){
        val actualResult = updateProfile()

        if (actualResult.equals("Method channel Success")) {
          result.success(actualResult)
        } else {
          result.error("UNAVAILABLE", "Result was not what I expected", null)
        }
      } else {
        result.notImplemented()
      }
    }

我想将 JSON/Map 数据传递到 Kotlin 端。我的数据如下所示:

{    
    "user_dob":"15 November 1997", 
    "user_description":"Hello there, I am a User!", 
    "user_gender":"Male", 
    "user_session":"KKDSH3G9OJKJFIHXLJXUGWIOG9UJKLJ98WHIJ"
}

如何将这些数据从 dart 传递到 kotlin?

4

3 回答 3

6

您可以通过方法调用传递参数。像,

var data = {    
"user_dob":"15 November 1997", 
"user_description":"Hello there, I am a User!", 
"user_gender":"Male", 
"user_session":"KKDSH3G9OJKJFIHXLJXUGWIOG9UJKLJ98WHIJ"
}

Future<void> _updateProfile() async {
    try {
      var result = await platform.invokeMethod('updateProfile', data);
      print(result);
    } on PlatformException catch (e) {
      print('Failed : ${e.message}');
    }
  }

并在 kotlin 中使用call.arguments

MethodChannel(flutterView, channel).setMethodCallHandler { call, result ->
     var argData = call.arguments       //you can get data in this object.
}
于 2019-11-18T05:49:07.410 回答
1

地图Json:

{    
    "user_dob":"15 November 1997", 
    "user_description":"Hello there, I am a User!", 
    "user_gender":"Male", 
    "user_session":"KKDSH3G9OJKJFIHXLJXUGWIOG9UJKLJ98WHIJ"
}

Kotlin 代码:</p>

MethodChannel(flutterView, channel).setMethodCallHandler { call, result ->
    //you can get data in this object.
    val user_dob = call.argument<String>("user_dob")
    val user_description = call.argument<String>("user_description")
    val user_gender = call.argument<String>("user_gender")
    val user_session = call.argument<String>("user_session")
}
于 2021-02-27T09:42:27.590 回答
0

飞镖端(发送地图):

var channel = MethodChannel('foo_channel');
var map = <String, dynamic>{
  'key': 'value',
};
await channel.invokeListMethod<String>('methodInJava', map);

Java端(接收Map):

if (methodCall.method.equals("methodInJava")) {
    // Map value.
    HashMap<String, Object> map = (HashMap<String, Object>) methodCall.arguments;
    Log.i("MyTag", "map = " + map); // {key=value}
}
于 2021-07-23T14:52:49.197 回答