问题:
如何捕获 Flutter app 的生命周期?
解决方法:
使用AppLifecycleState
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 new Text('Last notification: $_notification'); } }
App 状态变化时,会回调下面几个状态
inactive
paused
resumed
suspending