How to pass a message from Flutter to Native?

前端 未结 3 1704
醉梦人生
醉梦人生 2020-12-02 22:56

How would you pass info from Flutter back to Android/Native code if needed to interact with a specific API / hardware component?

Are there any Event Channels that c

相关标签:
3条回答
  • 2020-12-02 23:33

    Objective C

    call.arguments[@"parameter"]
    

    Android

    call.argument("parameter");
    
    0 讨论(0)
  • 2020-12-02 23:51

    Yes, flutter does has an EventChannel class which is what you are looking for exactly.

    Here is an example of that demonstrates how MethodChannel and EventChannel can be implemented. And this medium article shows how an EventChannel can be implemented in flutter.

    Hope that helped!

    0 讨论(0)
  • 2020-12-02 23:55

    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();
                        }
                    }
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题