Manage App Lifecycle in Flutter!

Do you wish to do something when the user minimizes your app? Let’s check out how you can do it!

Image copyright to the respective owner

So, to observe or manage the Lifecycle of our app, we have a class called in which we have access to an enum that has various lifecycle events. Let’s see those events one by one:

  • detached:
    The application is still hosted on a flutter engine but is detached from any host views. This means that the app or the engine is initializing while the view is not yet available for the user to interact with.
  • inactive:
    The application is in an inactive state and is not receiving user input. This means that the app is still in the foreground but the user is not interacting with your app. Usually, this state is encountered when the app is open and the user is in a phone call, responding to a TouchID request, opens notification panel, system dialog, picture-in-picture window, etc.
  • paused:
    This state is encountered when the application is not currently visible to the user, not responding to user input, and running in the background.
  • resumed:
    This state is encountered when the application is again in the foreground and is visible and responding to user input.

Let’s now see how you can listen to the AppLifecycle to check the state!

Step1: Add WidgetsBindingObserver to your class and add the observer.

The first step is the extend our stateful class with and add the observer in . We also need to remove the observer from the screen in method. Here’s a code snippet for the same:

So in this code, we have not added any UI components, we have just added the Scaffold(). We have extended our with . Then we added the observer of the current instance in and removed it in .

Step 2: Override

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
print('State: $state');
}

Now, if you wish to do something in a particular state, you can check which state it is using if conditions:

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
print('State: $state');
if (state == AppLifecycleState.resumed) print('App Resumed');
}

That was pretty simple right! You can do the same for the entire app by simply changing the class in from to and doing the same.

You can get the entire code for this article from my GitHub Repository!

Hope you enjoyed this article!

If you loved it, you can Buy Me A Coffee!

Don’t forget to connect with me on:

Don’t stop, until you are breathing!💙
- Abhishek Doshi

Flutter Developer