Flutter: Update Widgets On Resume?

后端 未结 6 1537
梦如初夏
梦如初夏 2020-12-01 03:06

In Flutter, is there a way to update widgets when the user leaves the app and come right back to it? My app is time based, and it would be helpful to update the time as soon

6条回答
  •  借酒劲吻你
    2020-12-01 03:25

    Simple way:

    import 'package:flutter/services.dart';
    
    handleAppLifecycleState() {
        AppLifecycleState _lastLifecyleState;
        SystemChannels.lifecycle.setMessageHandler((msg) {
    
         print('SystemChannels> $msg');
    
            switch (msg) {
              case "AppLifecycleState.paused":
                _lastLifecyleState = AppLifecycleState.paused;
                break;
              case "AppLifecycleState.inactive":
                _lastLifecyleState = AppLifecycleState.inactive;
                break;
              case "AppLifecycleState.resumed":
                _lastLifecyleState = AppLifecycleState.resumed;
                break;
              case "AppLifecycleState.suspending":
                _lastLifecyleState = AppLifecycleState.suspending;
                break;
              default:
            }
        });
      }
    

    just add handleAppLifecycleState() in your init()

    OR

    class AppLifecycleReactor extends StatefulWidget {
          const AppLifecycleReactor({ Key key }) : super(key: key);
    
          @override
          _AppLifecycleReactorState createState() => _AppLifecycleReactorState();
        }
    
        class _AppLifecycleReactorState extends State with WidgetsBindingObserver {
          @override
          void initState() {
            super.initState();
            WidgetsBinding.instance.addObserver(this);
          }
    
          @override
          void dispose() {
            WidgetsBinding.instance.removeObserver(this);
            super.dispose();
          }
    
          AppLifecycleState _notification;
    
          @override
          void didChangeAppLifecycleState(AppLifecycleState state) {
            setState(() { _notification = state; });
          }
    
          @override
          Widget build(BuildContext context) {
            return Text('Last notification: $_notification');
          }
        }
    

    For more details you refer documentation

提交回复
热议问题