Flutter: Update Widgets On Resume?

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

    You can listen to lifecycle events by doing this for example :

    import 'package:flutter/material.dart';
    import 'package:flutter/foundation.dart';
    
    class LifecycleEventHandler extends WidgetsBindingObserver {
      final AsyncCallback resumeCallBack;
      final AsyncCallback suspendingCallBack;
    
      LifecycleEventHandler({
        this.resumeCallBack,
        this.suspendingCallBack,
      });
    
      @override
      Future didChangeAppLifecycleState(AppLifecycleState state) async {
        switch (state) {
          case AppLifecycleState.resumed:
            if (resumeCallBack != null) {
              await resumeCallBack();
            }
            break;
          case AppLifecycleState.inactive:
          case AppLifecycleState.paused:
          case AppLifecycleState.detached:
            if (suspendingCallBack != null) {
              await suspendingCallBack();
            }
            break;
        }
      }
    }
    
    
    
    class AppWidgetState extends State {
      void initState() {
        super.initState();
    
        WidgetsBinding.instance.addObserver(
          LifecycleEventHandler(resumeCallBack: () async => setState(() {
            // do something
          }))
        );
      }
      ...
    }
    

提交回复
热议问题