Flutter: Update Widgets On Resume?

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 as it can.

1 answer

  • answered 2018-04-17 04:20 Günter Zöchbauer

    You can listen to lifecycle events

    class LifecycleEventHandler extends WidgetsBindingObserver {
      LifecycleEventHandler({this.resumeCallBack, this.suspendingCallBack});
    
      final FutureVoidCallback resumeCallBack;
      final FutureVoidCallback suspendingCallBack;
    
      @override
      Future<Null> didChangeAppLifecycleState(AppLifecycleState state) async {
        switch (state) {
          case AppLifecycleState.inactive:
          case AppLifecycleState.paused:
          case AppLifecycleState.suspending:
            await suspendingCallBack();
            break;
          case AppLifecycleState.resumed:
            await resumeCallBack();
            break;
        }
      }
    }
    
    
    class AppWidgetState extends State<AppWidget> {
      void initState() {
        super.initState();
    
        WidgetsBinding.instance.addObserver(
            new LifecycleEventHandler(resumeCallback(() => setState((){}))
        );
      }
      ...
    }