Dans Flutter, existe-t-il un moyen de mettre à jour les widgets lorsque l'utilisateur quitte l'application et y revient? Mon application est basée sur le temps, et il serait utile de mettre à jour l'heure dès que possible.
Vous pouvez écouter les événements du cycle de vie
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((){}))
);
}
...
}
Utilisation du canal système:
import 'package:flutter/services.Dart';
SystemChannels.lifecycle.setMessageHandler((msg){
debugPrint('SystemChannels> $msg');
if(msg==AppLifecycleState.resumed.toString())setState((){});
});
`
Manière simple:
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:
}
});
}
ajoutez simplement handleAppLifecycleState()
dans votre init()
OU
class AppLifecycleReactor extends StatefulWidget {
const AppLifecycleReactor({ Key key }) : super(key: key);
@override
_AppLifecycleReactorState createState() => _AppLifecycleReactorState();
}
class _AppLifecycleReactorState extends State<AppLifecycleReactor> 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');
}
}
Pour plus de détails, vous vous référez documentation