Search code examples
androidflutterandroid-lifecycle

How to handle android lifecycle in flutter android plugin package


I need to know the current state of the flutter app view in an android plugin package.

For now, I observe the state in the flutter view with https://docs.flutter.io/flutter/widgets/WidgetsBindingObserver-class.html and pass it then to my plugin.

As this seems sometimes not perfect (the first event is not passed on Android) I would like to get the state directly from the android plugin.

In the plugin I get the registrar and can its activity, but how do I observe the state of it?


Solution

  • Flutter doesn't provide hooks for these lifecycle events.

    Android Jetpack (formerly Architecture Components) added a nice way to receive lifecycle events from an activity:

    Handling Lifecycles with Lifecycle-Aware Components

    Downside: It only works when the activity is an AppCompatActivity. Flutter apps are usually based on a simple Activity, so you have to tell your users to use an AppCompatActivity instead.