如何检测flutter应用程序何时从后台返回?

Tre*_*ree 6 flutter

我想检测颤动应用程序何时从后台返回。

在其他跨App开发的SDK中,当应用程序更改此状态时,通常会有一个监听器。flutter中有类似的东西吗?

Tre*_*ree 9

class _AppState extends State<App> with WidgetsBindingObserver {
      
  @override
  void initState() {
    super.initState();
    //add an observer to monitor the widget lyfecycle changes
    WidgetsBinding.instance!.addObserver(this);
  }

  @override
  void dispose() {
    //don't forget to dispose of it when not needed anymore
    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
  }

  late AppLifecycleState _lastState;    
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if (state == AppLifecycleState.resumed && _lastState == AppLifecycleState.paused) {
      //now you know that your app went to the background and is back to the foreground
    }
    _lastState = state; //register the last state. When you get "paused" it means the app went to the background.
  }
}
Run Code Online (Sandbox Code Playgroud)