【问题标题】:Flutter Plugin With Kotlin, Activity always returns nullFlutter Plugin 使用 Kotlin,Activity 总是返回 null
【发布时间】:2020-01-29 12:24:07
【问题描述】:

当我在 Flutter 中按下我的 FAB 时,我正在尝试访问用 Kotlin 编写的 Flutter 插件中的活动引用。

我的班级是ActivityAware

代码如下: 科特林:

  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;
      }

【问题讨论】:

    标签: android kotlin flutter android-activity


    【解决方案1】:

    我找到了解决办法。

     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
    

    我后来能够找到活动参考。 无论如何谢谢:)

    【讨论】:

      猜你喜欢
      • 2021-02-21
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 2022-10-21
      • 2023-01-05
      • 2018-02-16
      • 1970-01-01
      相关资源
      最近更新 更多