Manage App Lifecycle in Flutter!

Abhishek Doshi
3 min readJul 28, 2021

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 WidgetsBindingObserver in which we have access to an enum AppLifecycleState 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 WidgetsBindingObserver and add the observer in initState() . We also need to remove the observer from the screen in dispose() 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 _HomeState with WidgetsBindingObserver . Then we added the observer of the current instance in initState() and removed it in dispose() .

Step 2: Override didChangeAppLifecycleState

@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 main.dart from Stateless to Statefull 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

--

--

Abhishek Doshi

Google Developer Expert — Dart, Flutter & Firebase 💙💛