onResume() and onPause() for widgets on Flutter

user3217522 picture user3217522 · Jun 2, 2017 · Viewed 20.3k times · Source

Right now, a widget only has initeState() that gets triggered the very first time a widget is created, and dispose(), which gets triggered when the widget is destroyed. Is there a method to detect when a widget comes back to the foreground? and when a widget is about to go to the background because another widget just was foregrounded? It's the equivalent of onResume and onPause being triggered for Android, and viewWillAppear and viewWillDisappear for ios

Answer

Mamnarock picture Mamnarock · Nov 30, 2017

There is an abstract class caller WidgetsBindingObserver

https://docs.flutter.io/flutter/widgets/WidgetsBindingObserver-class.html

in

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
            _notification = state;
    });
  }

there is the "state", can be manage as

switch(state) {
  case AppLifecycleState.resumed:
    // Handle this case
    break;
  case AppLifecycleState.inactive:
    // Handle this case
    break;
  case AppLifecycleState.paused:
    // Handle this case
    break;
  case AppLifecycleState.suspending:
    // Handle this case
    break;
}