How to exchange data between native and dart code in Flutter

Suppose you need to exchange data with the dart code (perhaps to update the UI) while a function is being executed in the native code. How do you do it? Here are the steps.

First, in the dart code, in the class wherein your MethodChannel is defined, create a method handler callback function and set it as the methodCallHandler in your class constructor.

class DeviceChannel {
  static const channel = MethodChannel('your/channel/path');


DeviceChannel(String deviceID, BuildContext context) {

    channel.setMethodCallHandler(_methodHandler);
    //Any other initializations if necessary
  }
  
  static Future<dynamic> _methodHandler(MethodCall call) async {
    switch (call.method) {
      case "gotDetails":
        if (call.arguments.containsKey("device")) {
         //Do something with the device details
       }
        break;
      case "history":
        log("Received history count: " + call.arguments.toString());
        //Do something with the history count
        break;
      default:
    }
  }

  //Rest of the channel functions

}

Next, in your native code, invoke the method wherever necessary, along with the arguments. You use the invokeMethod function for that. Here’s how this could be done in Kotlin:

val deviceChannel: MethodChannel = MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            'your/channel/path'
        )

//Somewhere in the code
deviceChannel.invokeMethod("history", 0)

//Somewhere else in the code
allRecordCount = min(response.body()!!.toInt(), 500)
                    
deviceChannel.invokeMethod("history", allRecordCount)

Similarly, here’s how you would do it in Objective C:

//Somewhere in the code
FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName: @"your/channel/path" binaryMessenger: self.fbm];

[channel invokeMethod:@"history" arguments: [NSString stringWithFormat: @"%d", 0]];

Thus, based on the values received by dart, your UI can keep updating even if the native function is still executing. This can help if you need to show a progress bar for especially long native functions.

I hope this article helped.


If you liked this article, then checkout other articles on https://iotespresso.com.

Leave a comment

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