DEV Community

Cover image for Flutter App life cycle
Prakash S
Prakash S

Posted on β€’ Edited on

3 1

Flutter App life cycle

Basically when we are writing a code for any Native applications, We will look for a life cycle events to handle some specific scenarios. Its like handling Thanos gauntlet snap to blip πŸ˜‡πŸ˜‡

Flutter comes with life cycle events to handle app life cycle for android & ios.

Let's see the code.

To consume the life cycle event, we need to have Stateful widget with WidgetsBindingObserver mixin.

class _HomePageState 
extends State<HomePage> 
with WidgetsBindingObserver {
Enter fullscreen mode Exit fullscreen mode

The mixin WidgetsBindingObserver provides an override didChangeAppLifecycleState where we will notified for certain app life cycle state changes.

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print('app resumed');
        break;
      case AppLifecycleState.paused:
        print('app paused');
        break;
      case AppLifecycleState.inactive:
        print('app inactive');
        break;
      case AppLifecycleState.detached:
      default:
        print('app detached');
        break;
    }
  }
Enter fullscreen mode Exit fullscreen mode

Finally to get work all these stuff, we need to inform or observe the app life cycle changes using

@override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
  }
Enter fullscreen mode Exit fullscreen mode

Ofcourse dont forget to remove observer on dispose

@override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance!.removeObserver(this);
  }
Enter fullscreen mode Exit fullscreen mode

That's it, we can now handle the app as per the app lifecycle.

For Full sample Github

Happy Fluttering πŸ˜‡πŸ˜‡

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Billboard image

πŸ“Š A side-by-side product comparison between Sentry and Crashlytics

A free guide pointing out the differences between Sentry and Crashlytics, that’s it. See which is best for your mobile crash reporting needs.

See Comparison

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay