How to invoke Method in native IOS to send data to Flutter?

3,662

I have tested. In general , use FlutterMethodChannel instance call invokeMethod. Now I show some test codes based batteryChannel demo.

In AppDelegate add one property

//didFinishLaunchingWithOptions methods

var batteryChannel : FlutterMethodChannel!

batteryChannel = FlutterMethodChannel.init(name: "samples.flutter.dev/battery", binaryMessenger: controller.binaryMessenger)

 private func receiveBatteryLevel(result: FlutterResult) {
        let device = UIDevice.current;
        device.isBatteryMonitoringEnabled = true;
        //test send message
        sendMessageToFlutter()
        if (device.batteryState == UIDevice.BatteryState.unknown) {
            result(FlutterError.init(code: "UNAVAILABLE",
                                     message: "Battery info unavailable",
                                     details: nil));
        } else {
            result(Int(device.batteryLevel * 100));
        }
    }

    private func sendMessageToFlutter(){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
            self.batteryChannel.invokeMethod("nativeCallSomeFlutterMethod", arguments: nil)
        }
    }

Now in flutter side , also based batteryChannel demo

class _MyHomePageState extends State<MyHomePage> {
 static const platform = const MethodChannel('samples.flutter.dev/battery');

 void initState(){
    super.initState();
    platform.setMethodCallHandler((call) {
         print("init state setMethodCallHandler ${call.method}");
    });
 }
}

after you click Get Battery Level button, 2seconds later ,you can see init state setMethodCallHandler nativeCallSomeFlutterMethod

Share:
3,662
Ahmed Abosrie
Author by

Ahmed Abosrie

Updated on November 21, 2022

Comments

  • Ahmed Abosrie
    Ahmed Abosrie over 1 year

    I need to send some data from the native IOS side to the dart side. I am using Channel Method to invoke the method from IOS side but I am getting noting:

    Flutter Side:

      static const platform = const MethodChannel('samples.flutter.dev/battery');
    platform.setMethodCallHandler(myUtilsHandler); // I am calling it in initState
    
      Future<dynamic> myUtilsHandler(MethodCall methodCall) async {
        print("myUtilsHandler");
        switch (methodCall.method) {
          case "someMethod":
            print(json.decode(methodCall.arguments));
            break;
          case 'someMethod2':
            print("someMethod2");
            break;
          default:
            print("default");
        }
      }
    

    Native IOS side:

    let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
        let batteryChannel = FlutterMethodChannel(name: "samples.flutter.dev/battery",binaryMessenger: controller.binaryMessenger)
    batteryChannel.invokeMethod("someMethod", arguments: "someValue")
    

    Note: the other way around is working fine!

    • Richard Heap
      Richard Heap almost 4 years
      All the best sample code lives in plugin projects, so it's a good idea to create a plugin project and depend on that from your main project. Also, make sure that you are calling invokeMethod from the main iOS thread.