didChangeAppLifecycleState

设置 app 应用处于切换app窗口隐藏内容!
我门可以通过这个方法 didChangeAppLifecycleState 来监听 整个app 到生命周期,该方法位于 WidgetsBindingObserver抽象类!

可监听状态

  1. resumed 正常状态 app可见状态
  2. inactive 窗口激活缩放到后台 app 可见状态
  3. puased 切换到另一个app 或者回到桌面 app 不可见状态
  4. detached app 后台 程序被关闭

resumed

resumed

inactive

inactive

puased

puased

detached

detached

案例

在根 app下引入WidgetsBindingObserver抽象类

demo
1
2
3
void main() {
runApp(const MyApp());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class MyApp extends StatefulWidget {
const MyApp({super.key});

@override
State<MyApp> createState() => MyAppState();
}

class MyAppState extends State<MyApp> with WidgetsBindingObserver {
bool hidden = false;

@override
void initState() {
// TODO: implement initState
super.initState();
WidgetsBinding.instance.addObserver(this);
}

@override
void dispose() {
// TODO: implement dispose
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}

// 检测整个 app 生命周期
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// TODO: implement didChangeAppLifecycleState
super.didChangeAppLifecycleState(state);
print(state);
/*
resumed 正常状态 app可见状态
inactive 窗口激活缩放到后台 app 可见状态
puased 切换到另一个app 或者回到桌面 app 不可见状态
detached app 后台 程序被关闭
*/
setState(() {
// 当应用切换至后台 或者 切换到 其他app时 做其他操作
hidden = state != AppLifecycleState.resumed;
});
}

@override
Widget build(BuildContext context) {
// TODO: implement build
// hidden 判断是否隐藏
return hidden
? const FlutterLogo()
: MaterialApp(
title: 'Flutter Mac App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blueGrey),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Mac App'),
);
}
}