onResume() and onPause() for widgets on Flutter

后端 未结 4 1150
故里飘歌
故里飘歌 2020-12-08 10:04

Right now, a widget only has initeState() that gets triggered the very first time a widget is created, and dispose(), which gets triggered when the widget is destroyed. Is t

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 10:38

    This is a full example demonstrating how to properly handle things, to test this, press home button and resume the app, you shall see didChangeAppLifecycleState is getting called.

    class HomePage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State with WidgetsBindingObserver {
      @override
      void initState() {
        super.initState();
    
        // add the observer
        WidgetsBinding.instance.addObserver(this);
      }
    
      @override
      void dispose() {
        // remove the observer
        WidgetsBinding.instance.removeObserver(this);
    
        super.dispose();
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        super.didChangeAppLifecycleState(state);
    
        // These are the callbacks
        switch (state) {
          case AppLifecycleState.resumed:
            // widget is resumed
            break;
          case AppLifecycleState.inactive:
            // widget is inactive
            break;
          case AppLifecycleState.paused:
            // widget is paused
            break;
          case AppLifecycleState.detached:
            // widget is detached
            break;
        }
      }
    
      @override
      Widget build(BuildContext context) => Scaffold();
    }
    

提交回复
热议问题