flutter didChangeAppLifecycleState never runs

无人久伴 提交于 2021-01-27 19:01:12

问题


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:


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();
}


来源:https://stackoverflow.com/questions/63641554/flutter-didchangeapplifecyclestate-never-runs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!