gpt4 book ai didi

android - Flutter Plugin 使用 Kotlin,Activity 总是返回 null

转载 作者:行者123 更新时间:2023-12-02 13:44:33 26 4
gpt4 key购买 nike

当我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com