US Office

1176 Shadeville Rd, Crawfordville Florida 32327, USA

 +1 (850) 780-1313

India Office

Office No 405, Kabir Shilp, Opp. Kansar Hotel, Opp. Landmark, Kudasan, Gandhinagar, Gujarat 382421

[email protected]

How to Pass Message From Flutter to Native ?

How to Pass Message From Flutter to Native

How to Pass Message From Flutter to Native ?

Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. As Flutter is a Cross-Platform App Development still we need to perform some operation in Flutter Mobile Application and move it to the Native Android Application. So in this article, we will learn about How to Pass Message From Flutter to Native?

How to Pass Message From Flutter to Native?

This is a simple implementation showcasing :

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

We will pass values from Flutter to Android like below:

  • Passing string value “text”.
    String text = "From Flutter to Android Pass Values";
    
    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;
    });
    }

    Now we need to get back a response from Native to Flutter like below:

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

Conclusion:

In this article, We have been through How to Pass Message From Flutter to Native?

Keep Learning !!! Keep Fluttering !!!

Still, need a Support for Flutter Development? Do let us know.

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 GuideFlutter ProjectsCode libs and etc.

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

Post a Comment