Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

android - How to pass a message from Flutter to Native?

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 can send info the other way or something similar to a callback?

  1. The platform_channel documentation points out "method calls can also be sent in the reverse direction, with the platform acting as client to methods implemented in Dart. A concrete example of this is the quick_actions plugin." I don't see how the native side is receiving a message from Flutter in this instance.
  2. It looks like a BasicMessageChannel’s send() method can be used to send "the specified message to the platform plugins on this channel". Can anyone provide a simple implementation example of this?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...