Flutter 之 Widget&App生命周期

Widget的生命周期
  • StatelessWidget

    StatelessElement createElement()
    Widget build(BuildContext context)
    
  • StatefulWidget


    image.png
    void initState()
    void didChangeDependencies()
    Widget build(BuildContext context)
    void reassemble()
    void didUpdateWidget(LifeCyclePage oldWidget)
    void deactivate()
    void dispose()
    
App的生命周期

App的生命周期需要通过WidgetsBindingObserver的didChangeAppLifecycleState来获取,在initState中添加监听WidgetsBinding.instance.addObserver(this);

resumed:可见并能响应用户的输入
inactiv:处在并不活动状态,无法处理用户响应
paused:不可见并不能响应用户的输入,但是在后台继续活动中

class LifeCyclePageAState extends State with WidgetsBindingObserver {
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print("app resumed");
        break;
      case AppLifecycleState.inactive:
        print("app inactive");
        break;
      case AppLifecycleState.paused:
        print("app paused");
        break;
      case AppLifecycleState.detached:
        print("app detached");
        break;
    }

    super.didChangeAppLifecycleState(state);
  }

  @override
  void initState() {
    print("initState A");
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }
  省略其他代码...
}

推到后台再回到前台打印如下


image.png

你可能感兴趣的:(Flutter 之 Widget&App生命周期)