Lifecycle in Flutter - WidgetsBindingObserver

Lifecycle in Flutter - WidgetsBindingObserver

Flutter a handy framework to work with even for a long time iOS developer like myself. One of the first questions that came to my mind when I first started with Flutter is: where is the basic app lifecycle!?

In iOS there are protocols in place for the UIAppDelegate like applicationDidBecomeActive, applicationDidEnterBackground, applicationWillResignActive, etc, and UIViewController with init(), viewDidLoad(), viewWillDisappear(), etc. These protocol are the keys to create Apps that retain the state for the next time it is (re)launched.

The anwser, at least for UIAppDelegate, is to use WidgetsBindingObserver. Start the project off with the default app, you should get something like this.

code.png

Modify the _MyHomePageState with the following code (just copy and paste):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  ...
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }
  @override
    void dispose() {
    super.dispose();
  }
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
    case AppLifecycleState.inactive:
    print("Inactive");
    break;
    case AppLifecycleState.paused:
    print("Paused");
    break;
    case AppLifecycleState.resumed:
    print("Resumed");
    break;
    case AppLifecycleState.suspending:
    print("Suspending");
    break;
  }
  ...
}

The class should look like this:

code.png

Run and test it, results:

result.png

It is just this simple, happy coding

comments powered by Disqus