Send Map/JSON from Flutter to Android through Method channel

Issue

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?

Solution

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.
}

Answered By – Abhay Koradiya

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *