How to Pass a Message From Flutter to Native ??

3 min read
How to Pass a Message From Flutter to Native
How to Pass a Message From Flutter to Native

Earlier we have been through various flutter articles about how to delete a firebase storage file with flutter. So in today’s article, we will go through how to pass a Message From Flutter to Native…

How to Pass a Message From Flutter to Native ??

This is a simple implementation showcasing:

  • Passing a string Value from the flutter to Android code
  • Getting back response from Android code to flutter

code is based on an 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 “battery-level” 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();
                    }
                }

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

Objective C will have a code snippet like the below:

call.arguments[@"parameter"]

Android will have a code snippet like the below:

call.argument("parameter");

Conclusion:

So, Hope you have learned from this post 馃檪

So in this article, we have been through how to pass a message from the flutter to native…

Do not forget to drop your valuable suggestions/feedback. We would love to assist you.

FlutterAgency.com聽is our portal Platform dedicated to聽Flutter聽Technology and聽Flutter Developers. The portal is full of cool resources from Flutter like聽Flutter Widget聽Guide,聽Flutter Projects,聽Code libs聽and etc.

FlutterAgency.com聽is one of the most popular online portals dedicated to聽Flutter Technology聽and daily thousands of unique visitors come to this portal to enhance their knowledge of聽Flutter.

Leave a Reply