Calling a function and passing arguments from Kotlin to Flutter

4,578

Solution 1

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")



            }
        }

    }

Solution 2

This ended up working on my end. If you want to invoke your methods inside of android lifecycle callbacks, try something like this

const val CHANNEL = "yourTestChannel"

class MainActivity : FlutterActivity() {

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

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    var flutterEngine = FlutterEngine(this)

    flutterEngine
      .dartExecutor
      .executeDartEntrypoint(
        DartExecutor.DartEntrypoint.createDefault()
      )

    var channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)

    channel.invokeMethod("yourMethod", "yourArguments")
    }
  }
}
Share:
4,578
codeKiller
Author by

codeKiller

Updated on December 17, 2022

Comments

  • codeKiller
    codeKiller over 1 year

    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.