62

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?

6 Answers 6

112

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();
        }
    }
    
9
  • how to get a list of string
    – Yeahia2508
    Commented Sep 22, 2018 at 11:50
  • @Yeahia2508 do you have the answer?
    – Gregga17
    Commented Oct 10, 2018 at 9:06
  • I solved my problem using other method. stackoverflow.com/questions/52456013/…
    – Yeahia2508
    Commented Oct 11, 2018 at 9:44
  • @Yeahia2508 I have find a solution to do it on the good way. If you are still interested, let me know
    – Gregga17
    Commented Oct 17, 2018 at 8:24
  • Please add your answer in my so question. @Gregga17
    – Yeahia2508
    Commented Oct 19, 2018 at 13:25
8

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
8

Objective C

call.arguments[@"parameter"]

Android

call.argument("parameter");
5
  • What about android?
    – Sabrina
    Commented Dec 30, 2019 at 17:17
  • 1
    Android - Java ---> call.argument("parameter"); Commented Dec 30, 2019 at 20:44
  • how about in kotlin
    – H Zan
    Commented Aug 19, 2020 at 3:08
  • @HZan, in Kotlin: val s: String? = call.argument("parameter") Commented Sep 5, 2020 at 20:41
  • @HZan What about the CPP window side? Commented Mar 15, 2023 at 21:22
7

Passing from Flutter to native:

await platform.invokeMethod(
  'runModel', 
  {'path': imagePath!.path} // 'path' is the key here to be passed to Native side
);

For Android (Kotlin):

val hashMap = call.arguments as HashMap<*,*> //Get the arguments as a HashMap

val path = hashMap["path"] //Get the argument based on the key passed from Flutter

For iOS (Swift):

guard let args = call.arguments as? [String : Any] else {return}
let text = args["path"] as! String
6

for swift

    guard let args = call.arguments as? [String : Any] else {return}
    let phoneNumber = args["contactNumber"] as! String
    let originalMessage = args["message"] as! String
0

If anyone wants to share the data from native to flutter with invoke method follow this:

main.dart

Future<dynamic> handlePlatformChannelMethods() async {
  platform.setMethodCallHandler((methodCall) async {
   if (methodCall.method == "nativeToFlutter") {
     String text = methodCall.arguments;
     List<String> result = text.split(' ');
     String user = result[0];
     String message = result[1];
    }
   }
  }

MainActivity.java

 nativeToFlutter(text1:String?,text2:String?){
 MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, 
  CHANNEL.invokeMethod("nativeToFlutter",text1+" "+text2);
 }
2
  • How could I share the data from flutter to Android native.
    – Rethinavel
    Commented May 17, 2022 at 12:32
  • Hi, you can follow this link Commented May 20, 2022 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.