How to send a list of data from flutter to android java method channels or eventChannels?

971 Views Asked by At
  void sendData() async {
    final session = StateInheritedWidget.of(context).state.session;
    String Datas;
    try {
      final String result = await sendData.invokeMethod(
          'sendData',{"bVolt":1.5,"hstring":2.5,
            "qString":3.5,"ExternalDeg":5.5,
        "extDeg":6.5,"sessionNo":int.tryParse(session) ?? 0});
      Datas = 'sendData response $result % .';
    } on PlatformException catch (e) {
      Datas = "Failed to get session response: '${e.message}'.";
    }
  }

Here I am passing a string data, I want to pass object data from database and send to android java and retrieve that data from java , How its possible through method channel?

1

There are 1 best solutions below

12
On

You can Send it as List of Map like this:

List<Map> data = [
        {
           "bVolt":1.5,
           "hstring":2.5,
           "qString":3.5,
           "ExternalDeg":5.5,
           "extDeg":6.5,
           "sessionNo":int.tryParse(session) ?? 0
        }
];

final String result = await sendData.invokeMethod('sendData',data);

and in android part (kotlin) you can try this:

val data = (call.arguments) as List;
for (item:Map<String, Any> in data) {
  Log.d("", "item = $item");  
}

and in your java part you can make a for loop and access your data:

new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
        .setMethodCallHandler(
          (call, result) -> {
               if (call.method.equals("sendData")) {
                 var data = (List<Map<String, Object>>)call.arguments;
                 for (Map<String, Object> item : data){
                     Log.d("", "item = $item");  
                 }
               } else {
                 result.notImplemented();
               }
          }
        );