Flutter: Update Widgets On Resume?

后端 未结 6 1541
梦如初夏
梦如初夏 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:23

    Here’s an example of how to observe the lifecycle status of the containing activity (Flutter for Android developers):

    import 'package:flutter/widgets.dart';
    
    class LifecycleWatcher extends StatefulWidget {
      @override
      _LifecycleWatcherState createState() => _LifecycleWatcherState();
    }
    
    class _LifecycleWatcherState extends State with WidgetsBindingObserver {
      AppLifecycleState _lastLifecycleState;
    
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        setState(() {
          _lastLifecycleState = state;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        if (_lastLifecycleState == null)
          return Text('This widget has not observed any lifecycle changes.', textDirection: TextDirection.ltr);
    
        return Text('The most recent lifecycle state this widget observed was: $_lastLifecycleState.',
            textDirection: TextDirection.ltr);
      }
    }
    
    void main() {
      runApp(Center(child: LifecycleWatcher()));
    }
    

提交回复
热议问题