didChangeAppLifecycleState
设置 app 应用处于切换app窗口 时隐藏内容!
我门可以通过这个方法 didChangeAppLifecycleState 来监听 整个app 到生命周期,该方法位于 WidgetsBindingObserver抽象类!
可监听状态
resumed 正常状态 app可见状态inactive 窗口激活缩放到后台 app 可见状态puased 切换到另一个app 或者回到桌面 app 不可见状态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() { super.initState(); WidgetsBinding.instance.addObserver(this); }
@override void dispose() { super.dispose(); WidgetsBinding.instance.removeObserver(this); }
@override void didChangeAppLifecycleState(AppLifecycleState state) { super.didChangeAppLifecycleState(state); print(state);
setState(() { hidden = state != AppLifecycleState.resumed; }); }
@override Widget build(BuildContext context) { 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'), ); } }
|