使用AppLifecycleListener 来监听 想在那个页面监听就在那个页面初始化 别忘记还有销毁

Dart
class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsFlutterBinding.ensureInitialized(); // 确保初始化Flutter的绑定
WidgetsBinding.instance!.addObserver(this); // 添加观察者
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// 在这里处理生命周期事件
switch (state) {
case AppLifecycleState.inactive:
print('App is inactive');
break;
case AppLifecycleState.resumed://进入前台
print('App is resumed');
break;
case AppLifecycleState.paused://进入后台
print('App is paused');
break;
case AppLifecycleState.detached:
print('App is suspending');
break;
case AppLifecycleState.hidden:
// TODO: Handle this case.
throw UnimplementedError();
}
}
@override
void dispose() {
WidgetsBinding.instance!.removeObserver(lifecycleHandler); // 移除观察者
super.dispose();
}
}