How to handle app lifecycle with Flutter (on Android and iOS)?

There is a method called when the system put the app in the background or return the app to foreground named didChangeAppLifecycleState.

Example with widgets:

  class _AppLifecycleReactorState extends State<AppLifecycleReactor> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  AppLifecycleState _notification;

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

  @override
  Widget build(BuildContext context) {
    return new Text('Last notification: $_notification');
  }
}

Also there are CONSTANTS to know the states that an application can be in, eg:

  1. inactive
  2. paused
  3. resumed
  4. suspending

The usage of these constants would be the value of the constant e.g:

const AppLifecycleState(state)

Leave a Comment