4

Flutter App life cycle

 2 years ago
source link: https://dev.to/prakashselvaraj/flutter-app-life-cycle-1jim
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cover image for Flutter App life cycle

Flutter App life cycle

Sep 1

・1 min read

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 modeExit 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 modeExit 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 modeExit fullscreen mode

Ofcourse dont forget to remove observer on dispose

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

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

Happy Fluttering 😇😇


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK