androidflutterkotlindartflutter-channel

Can I call Kotlin function from Dart


Using Flutter, a kotlin/swift function can be called by something like:

file.dart:

static const platform = const MethodChannel('my.test.flutterapp/battery');
final int result = await platform.invokeMethod('getBatteryLevel');

file.kt:

private val CHANNEL = "my.test.flutterapp/battery"
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
          if (call.method == "getBatteryLevel") {
              ...
          } else {
              result.notImplemented()
          }
      }

Is there something similar to call Kotlin function from standard Dart app, like Dart console app!


Solution

  • For the VM the mechanisms available are basic OS operations and native extensions.

    By OS operations I mean, you could launch a separate process and interact with it, using files or the network stack. This is probably not as fine grained as you're looking for.

    Native extensions allow you to call out to C or C++ code. I don't know enough about kotlin to know if you can easily expose functionality to C/C++. If it's possible, this will give you the tightest integration.

    https://www.dartlang.org/articles/dart-vm/native-extensions