Flutter 判断应用是否在前台

6 min read

如果想要知道 Flutter App 的生命周期,例如 Flutter 是在前台还是在后台,就需要使用到 WidgetsBindingObserver 了,使用方法如下:

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
    ...
}

添加监听

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

移除监听

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

判断生命周期

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  super.didChangeAppLifecycleState(state);
  if (state == AppLifecycleState.paused) {
    // went to Background
  }
  if (state == AppLifecycleState.resumed) {
    // came back to Foreground
  }
}

AppLifecycleState 就是 App 的生命周期,有:

  • resumed
  • inactive
  • paused
  • suspending