How to Pass a Message from Flutter to Native

How to pass a message from Flutter to Native?

This is a simple implementation showcasing:

  1. Passing a string Value from flutter to Android code
  2. Getting back response from Android code to flutter

Code is based on example from: https://flutter.io/platform-channels/#codec

  1. Passing string value "text":

    String text = "whatever";

    Future<Null> _getBatteryLevel(text) async {
    String batteryLevel;
    try {
    final String result = await platform.invokeMethod('getBatteryLevel',{"text":text});
    batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
    batteryLevel = "Failed to get battery level: '${e.message}'.";
    }

    setState(() {
    _batteryLevel = batteryLevel;
    });

  2. Getting back response "batterylevel" after RandomFunction();

    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
    if (call.method.equals("getBatteryLevel")) {

    text = call.argument("text");
    String batteryLevel = RandomFunction(text);

    if (batteryLevel != null) {
    result.success(batteryLevel);
    } else {
    result.error("UNAVAILABLE", "Battery level not available.", null);
    }
    } else {
    result.notImplemented();
    }
    }

How to call arguments from Flutter in Swift native code?

You are passing a Map from Dart to native: {"isDebug": isDebug}, so you need extract the parameter from the map/dictionary at the Swift end.

  if let args = call.arguments as? Dictionary<String, Any>,
let isDebug = args["isDebug"] as? Bool {
// please check the "as" above - wasn't able to test
// handle the method

result(nil)
} else {
result(FlutterError.init(code: "errorSetDebug", message: "data or format error", details: nil))
}

Alternatively, just pass the boolean from the Dart end, without first putting it into a map.

_channel.invokeMethod('setDebugEnabled', isDebug);

Flutter plugin - MethodChannel: .invokeMethod() from native iOS to Flutter never reaches Flutter part

So, the reason of described behavior itself (in my particular case) was definitely in changing root view controller from FlutterViewController to my custom iOS UIViewController (reason - plugin had a reference to native SDK which used its own storyboard).

Seems there wasn't any feature request yet to clarify that inconvenience for native iOS plugin users in documentation/readme.

UPD: there is an issue which describes possible reasons of merely expected behaviour: https://github.com/flutter/flutter/issues/52456



Related Topics



Leave a reply



Submit