Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Update Widgets On Resume?

Tags:

flutter

dart

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.

like image 795
Josh Avatar asked Apr 17 '18 04:04

Josh


1 Answers

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<void> 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<AppWidget> {   void initState() {     super.initState();      WidgetsBinding.instance.addObserver(       LifecycleEventHandler(resumeCallBack: () async => setState(() {         // do something       }))     );   }   ... } 
like image 52
Günter Zöchbauer Avatar answered Oct 02 '22 13:10

Günter Zöchbauer