How to call methods in Dart portion of the app, from the native platform using MethodChannel?

CodeWithFlutter
2 Min Read

In Flutter, you can use the MethodChannel class from the flutter package to call methods in the Dart portion of the app from the native platform (iOS or Android). Here’s a simple example of how you can use the MethodChannel class:

  1. Define a unique name for the MethodChannel in Dart:
static const platform = const MethodChannel('my_channel');

In the native platform code, you can use the same name to create a MethodChannel object and call methods on it. For example, in iOS:

let channel = FlutterMethodChannel(name: "my_channel", binaryMessenger: controller)
channel.setMethodCallHandler({
  (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
  switch call.method {
    case "myMethod":
      // Perform some action
      result("Success")
    default:
      result(FlutterMethodNotImplemented)
  }
})

And in Android:

MethodChannel channel = new MethodChannel(flutterView, "my_channel");
channel.setMethodCallHandler(new MethodCallHandler() {
  @Override
  public void onMethodCall(MethodCall call, MethodChannel.Result result) {
    switch (call.method) {
      case "myMethod":
        // Perform some action
        result.success("Success");
        break;
      default:
        result.notImplemented();
        break;
    }
  }
});

In Dart, you can call the method on the MethodChannel using the invokeMethod method:

String result = await platform.invokeMethod('myMethod');
print(result);

In this example, the myMethod method is called on the native platform code, and the result is passed back to the Dart code. You can pass arguments to the method and receive the result by using the call.arguments and result objects, respectively.

Share this Article
Leave a comment