Flutter1.12与原生Android交互(kotlin)

开发原生部分,还是点击Open for Editing in Android Studio好用,提示、自动引用功能都能正常使用。

 

-----------android/app/src/main/kotlin/com/glodon/gzzjy_app/MainActivity.kt

 

import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger,"app.channel.shared.data").setMethodCallHandler(
            MethodChannel.MethodCallHandler { call, result ->
                run {
                    if (call.method.contentEquals("getParam")) {
                        result.success("message")
                        Log.i("test","ms")
                    }
                }
            }
        )
    }

}

 

注:这个flutterEngine.dartExecutor.binaryMessenger找了好久,各种文档上都是写的继承于io.flutter.app.FlutterActivity的MainActivity,直接getFlutterView()就行了,但是1.12这个版本的不行了。

------------------lib/main.dart



class _MyHomePageState extends State {
  static const platform = const MethodChannel('app.channel.shared.data');
  String dataShared = "No data";

  @override
  void initState() {
    super.initState();
    getSharedText();
  }

  getSharedText() async {
    var sharedData = await platform.invokeMethod("getParam");
    if (sharedData != null) {
      setState(() {
        dataShared = sharedData;
      });
      print(dataShared);
    }
  }

你可能感兴趣的:(flutter,android,kotlin)