简体   繁体   中英

How can I run Kotlin function in Flutter?

I followed what Flutter did in https://flutter.dev/docs/development/platform-integration/platform-channels but it didn't work. I checked other people's work and still nothing. So what do you guys suggest?

class MainActivity: FlutterFragmentActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this.getFlutterEngine()!!)
}


private val CHANNEL = "samples.flutter.dev/battery"

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
        call, result ->
        if (call.method == "MyMethod"){
            result.success("Hello Kotlin")
        }
    }
}}

and this is the method in flutter itself

static const platform = 
const MethodChannel("samples.flutter.dev/battery");


Future<void> MyMethod() async {
String value = "";

try{
  value = await platform.invokeMethod("MyMethod");
}
catch(e){
  print(e);
}
print(value);
}

Please, I've tried everything on internet but none of them worked. I beg your help for my case.

I just solved my issue. It was in AndroidManifest.xml

it was

 android:name="io.flutter.embedding.android.FlutterFragmentActivity"

I changed it back to

   android:name=".MainActivity"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM