Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments from Flutter to Kotlin?

i've got started studying Flutter. I'm trying to using MethodChannel and MethodCall to communicate with Android platform. I don't know how to pass arguments to the Android code.

Below is my code.

// dart
void _onClick() async {
    var parameters = {'image':'starry night'};
    await platform.invokeMethod('showToast', new Map.from(parameters));
}


// kotlin
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
    Log.d("MainActivity", ">> ${call.method}, ${call.arguments}")
    when (call.method) {
        "showToast" -> {
        showToast("toast")
    }
    else -> {
        Log.d("MainActivity", "fail");
    }
}

I can check an arguement value what I passed by log message what I printed. {image=starry night} But I don't know how to parse to a map object.

like image 215
Kyoung-june Yi Avatar asked Mar 11 '18 09:03

Kyoung-june Yi


People also ask

Is Flutter harder than Kotlin?

In simple words, Flutter is faster than Kotlin. But Kotlin has much more to offer. It has concise syntax and code reusability features which also results in the more rapid development of apps. Both frameworks save development time to a great extent.

Which is faster Kotlin or Flutter?

Flutter seems a bit faster than Kotlin. However, Kotlin has much more to offer. Its concise syntax and code reusability results in faster app development and quick app-to-market-time.


1 Answers

Flutter

On the Flutter side, you can pass arguments by including them as a map in the invokeMethod call.

_channel.invokeMethod('showToast', {'text': 'hello world'});

Kotlin

On the Kotlin side you can get the parameters by casting call.arguments as a Map or getting a particular argument from call.argument().

override fun onMethodCall(call: MethodCall, result: Result) {
  when (call.method) {
    "showToast" -> {
      val text = call.argument<String>("text") // hello world
      showToast(text)
    }   
  }
}
like image 158
Suragch Avatar answered Oct 12 '22 06:10

Suragch