简体   繁体   中英

Flutter Plugin With Kotlin, Activity always returns null

I am trying to access the activity reference in a Flutter Plugin written in Kotlin when I press my FAB within Flutter.

My class is ActivityAware

Here is the code: 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()
    }
  }

The dart code (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;
      }

I found a solution.

 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
  }

By setting:

myplugin.myActivity

I was able to find the activity reference later. Anyways thanks :)

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