Flutter app 存在如下 4 种状态,paused
和 resumed
在 iOS 和 Andriod 上都存在。
如下代码,当 app 状态改变时,print 状态:
// mixin 语法
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print(state);
}
// 当不再需要该state object时,清除 lifecycle listener
@override
dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
例如:
I/flutter (20551): AppLifecycleState.inactive
I/flutter (20551): AppLifecycleState.paused
I/flutter (20551): AppLifecycleState.resumed
I/flutter (20551): AppLifecycleState.inactive
I/flutter (20551): AppLifecycleState.paused
I/flutter (20551): AppLifecycleState.detached
Lost connection to device. // 关闭 app
https://medium.com/pharos-production/flutter-app-lifecycle-4b0ab4a4211a