flutter didChangeAppLifecycleState never runs

Viewed 2947

I implemented the WidgetsBindingObserver, but the app is NEVER sent to the background so it doesn't recognize the AppLifecycleState.resumed

this is the current implementation


  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    print('\n\ndidChangeAppLifecycleState');
    switch (state) {
      case AppLifecycleState.resumed:
        print('\n\nresumed');
        _mymethod();
        break;
      case AppLifecycleState.inactive:
        print('\n\ninactive');
        break;
      case AppLifecycleState.paused:
        print('\n\npaused');
        break;
      case AppLifecycleState.detached:
        print('\n\ndetached');
        break;
    }
  }

to simulate the process i do the next in android

  1. run the project as --release
  2. open the widget with the WidgetsBindingObserver
  3. open another app (like chrome or phone settings)
  4. return to the app

when returning to the app i can see my widget on screen, the app doesn't restart, but NONE of the prints appears on the console not event the print('\n\ndidChangeAppLifecycleState'); and _mymethod(); is never executed

1 Answers

The WidgetsBindingObserver mixin requires a bit more work than merely implementing the interface. You also need to add the following to your widget state class:

@override
void initState() {
  super.initState();
  WidgetsBinding.instance.addObserver(this);
}

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