Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function and passing arguments from Kotlin to Flutter

I am dealing with PlatformChannels trying to communicate from Kotlin to Flutter. Trying actually to do what it is explained on the docs from flutter platform channels, but on the opposite direction:

flutter platfor channels docs

The idea is to call a Flutter function from the configureFlutterEngine function on the MainActivity.kt class.

For that, i do, on Flutter side, main.dart (default example from Flutter):

   class _MyHomePageState extends State<MyHomePage> {

  static const platformChannel = const MethodChannel('myTestChannel');


  @override
  Widget build(BuildContext context) {

    platformChannel.setMethodCallHandler((call){
      print("Hello from ${call.method}");
      return null;
    });


    //
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          //
          //
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
          ],
        ),
      ),
    );
  }
}

And from the Kotlin side, i just try to call the flutter callback method on MainActivity.kt:

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)

        val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "myTestChannel")

        channel.invokeMethod("myTestChannel","the argument from Android")
}

But nothing is printed on the Flutter side when I run the code. No crashes or exception either.

like image 540
codeKiller Avatar asked Nov 01 '25 21:11

codeKiller


1 Answers

You should be implement below way

Dart Code

method_channel_helper.dart

class AmazonFileUpload {
  static const platform = const MethodChannel('amazon');
  static StreamController<String> _controller = StreamController.broadcast();

  static Stream get streamData => _controller.stream;

  Future<BaseResponse> uploadFile() async {
    try {
      platform.setMethodCallHandler((call) {
        switch (call.method) {
          case "callBack":
            _controller.add("");
            break;
        }
      });
      final Map result = await platform.invokeMethod('s3_upload');
      return BaseResponse(result["success"], result["error"], "");
    } on PlatformException catch (e) {
      return BaseResponse(false, e.message, "");
    }
  }
}

home_page.dart

class _HomePageState extends State<HomePage> {

  @override
  void initState() {
    super.initState();
    AmazonFileUpload.streamData.listen((event) {
      print("========$callbackFromKotlinToDart--------");
    });
    AmazonFileUpload().uploadFile();



  @override
  Widget build(BuildContext context) {

}

Android Code

class MainActivity : FlutterActivity(), TransferListener {
    private val CHANNEL = "amazon"

    var methodResult: MethodChannel.Result? = null
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)

        channel.setMethodCallHandler { call, result ->
            methodResult = result
            if (call.method == "s3_upload") {
                //Add you login here 
                channel.invokeMethod("callBack", "data1")



            }
        }

    }
like image 91
Nikhil Vadoliya Avatar answered Nov 04 '25 10:11

Nikhil Vadoliya