Flutter生命周期及监听状态

2021-03-28  本文已影响0人  Michale_Zuo

Flutter Widget生命周期分为3个阶段:

1.创建:

2.更新:

3.销毁:

Flutter 状态监听WidgetsBinding

1.遵守WidgetsBindingObserver协议
2.initState添加观察者:WidgetsBinding.instance.addObserver(this);
3.dispose 移除观察者:WidgetsBinding.instance.removeObserver(this);
4.重写didChangeAppLifecycleState

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

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

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

    if (state == AppLifecycleState.resumed) {
      print("app进入前台");
    } else if (state == AppLifecycleState.inactive) {
      print("app在前台但不响应事件,比如电话,touch id等");
    } else if (state == AppLifecycleState.paused) {
      print("app进入后台");
    } else if (state == AppLifecycleState.detached) {
      print("没有宿主视图但是flutter引擎仍然有效");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
上一篇下一篇

猜你喜欢

热点阅读