How to pass a message from Flutter to Native?

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

Leave a Comment