Home > Software engineering >  Flutter plugin - How to deregister Lifecycle listeners?
Flutter plugin - How to deregister Lifecycle listeners?

Time:12-29

I am trying to implement a Flutter plugin and so I am checking the [docs][1] for ActivityAware

And for onDetached it says this:

void onDetachedFromActivity() This plugin has been detached from an Activity. Detachment can occur for a number of reasons.

The app is no longer visible and the Activity instance has been destroyed. The FlutterEngine that this plugin is connected to has been detached from its FlutterView. This ActivityAware plugin has been removed from its FlutterEngine. By the end of this method, the Activity that was made available in onAttachedToActivity(ActivityPluginBinding) is no longer valid.

Any references to the associated Activity or ActivityPluginBinding should be cleared.

Any Lifecycle listeners that were registered in onAttachedToActivity(ActivityPluginBinding) or onReattachedToActivityForConfigChanges(ActivityPluginBinding) should be deregistered here to avoid a possible memory leak and other side effects.

How do I actually deregister listeners? Let's say this is my onAttachedToActivity.

override fun onAttachedToActivity(binding: ActivityPluginBinding) {
  currentActivity = binding.activity
  binding.addRequestPermissionsResultListener(this)

}

What do I put inside my onDetached to clean everything up? Thank you.

[1]: https://api.flutter.dev/javadoc/io/flutter/embedding/engine/plugins/activity/ActivityAware.html#onReattachedToActivityForConfigChanges(io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding

CodePudding user response:

You can use binding.removeRequestPermissionsResultListener(this) inside onDetachedFromActivity()

More info: https://api.flutter.dev/javadoc/io/flutter/embedding/engine/plugins/activity/ActivityPluginBinding.html#removeRequestPermissionsResultListener(io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener)

  • Related