Flutter 如何监听App页面是否隐藏

使用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();
}
}
相关推荐
xingpanvip9 分钟前
星盘接口开发文档:组合三限盘接口指南
android·开发语言·前端·python·php·lua
阿拉丁的梦19 分钟前
blender最好的多通道吸色工具(拾取纹理颜色排除灯光)
前端·html
吴声子夜歌20 分钟前
Vue3——脚手架Vite
前端·javascript·vue.js·vite
摘星编程22 分钟前
当AI开始学会“使用工具“——从ReAct到MCP,大模型如何获得真正的行动力
前端·人工智能·react.js
light blue bird30 分钟前
设备数据变化上传图表数据汇总组件
大数据·前端·信息可视化
2501_9181269136 分钟前
开源祭祖网页index
前端·开源·html
maaath41 分钟前
【maaath】Flutter for OpenHarmony 闹钟时钟应用开发实战
flutter·华为·harmonyos
maaath1 小时前
【maaath】Flutter for OpenHarmony 短信管理应用实战
flutter·华为·harmonyos
傻瓜搬砖人1 小时前
SpringMVC的请求
java·前端·javascript·spring
爱上好庆祝1 小时前
学习js的第六天(js基础的结束)
开发语言·前端·javascript·学习·ecmascript