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.
In Flutter app development, there are situations where you need to communicate with native platform functionalities or libraries. Passing messages from Flutter to the native side becomes essential for achieving seamless integration and unlocking platform-specific capabilities.
In this blog post, we’ll provide you with a comprehensive guide on how to pass messages from Flutter to native platforms. Whether you’re a beginner or an experienced Flutter developer, this guide will equip you with the necessary knowledge to establish communication channels between Flutter and the native side of your app.
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.