当我在 Flutter 中按下我的 FAB 时,我试图访问用 Kotlin 编写的 Flutter Plugin 中的 Activity 引用。
我的类(class)是ActivityAware
这是代码:
Kotlin :
lateinit var myActivity: Activity
//Method called by ActivityAware plugins to fetch the activity on re-initialization
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
this.myActivity = binding.activity
}
//Method called by ActivityAware plugins to fetch the activity on initialization
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
this.myActivity = binding.activity
}
//With this method is called from Flutter to check if the Activity is accessible.
//In this case it is always returning null/ not initialized
//It prints "FAILED AGAIN!!"
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "checkForActivity") {
if(::myActivity.isInitialized){
System.out.println("I FOUND IT!!")
}else{
System.out.println("FAILED AGAIN!!")
}
return
} else {
result.notImplemented()
}
}
飞镖代码( flutter ):
//This Flutter class is run whenever you press a button to check for the Activity in Native Kotlin.
static const MethodChannel _channel =
const MethodChannel('sphinx_plugin');
static Future<bool> get checkForActivity async {
final bool isready = await _channel.invokeMethod('checkForActivity');
return isready;
}
最佳答案
我找到了解决方案。
lateinit var myplugin: MyPlugin()
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
myplugin = MyPlugin()
val channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "my_plugin")
channel.setMethodCallHandler(myplugin)
}
//This is where I was going wrong..The reference was being lost somewhere
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
myplugin.myActivity = binding.activity
}
通过设置:
myplugin.myActivity
后来我能够找到 Activity 引用。
无论如何谢谢:)
关于android - Flutter Plugin 使用 Kotlin,Activity 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59967030/