Reputation: 1244
I've set up a basic method channel in Dart and Kotlin
Dart Code
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 Code
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()
}
}
I want to pass a JSON/Map data to the Kotlin side. My data looks like this:
{
"user_dob":"15 November 1997",
"user_description":"Hello there, I am a User!",
"user_gender":"Male",
"user_session":"KKDSH3G9OJKJFIHXLJXUGWIOG9UJKLJ98WHIJ"
}
How can I pass this data from dart to kotlin?
Upvotes: 5
Views: 7639
Reputation: 268054
Dart side (sending Map):
var channel = MethodChannel('foo_channel');
var map = <String, dynamic>{
'key': 'value',
};
await channel.invokeListMethod<String>('methodInJava', map);
Java side (receiving Map):
if (methodCall.method.equals("methodInJava")) {
// Map value.
HashMap<String, Object> map = (HashMap<String, Object>) methodCall.arguments;
Log.i("MyTag", "map = " + map); // {key=value}
}
Upvotes: 0
Reputation: 2797
Map Json:
{
"user_dob":"15 November 1997",
"user_description":"Hello there, I am a User!",
"user_gender":"Male",
"user_session":"KKDSH3G9OJKJFIHXLJXUGWIOG9UJKLJ98WHIJ"
}
Kotlin Code:
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")
}
Upvotes: 1
Reputation: 2117
You can pass parameter with method call. Like,
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}');
}
}
And get result in kotlin using call.arguments
MethodChannel(flutterView, channel).setMethodCallHandler { call, result ->
var argData = call.arguments //you can get data in this object.
}
Upvotes: 8