Flutter中的AppLifecycleListener:应用生命周期监听器介绍及使用

引言

当你在Flutter中需要监听应用程序的生命周期变化时,可以使用AppLifecycleListener。在Flutter 3.13中,AppLifecycleListener被添加到Framework中,用于监听应用程序的生命周期变化,并响应退出应用程序的请求等支持。

在Flutter 3.13之前,我们通常使用WidgetsBindingObserver的didChangeAppLifecycleState方法来实现生命周期的监听。但是,didChangeAppLifecycleState方法比较"粗暴",直接返回AppLifecycleState让用户自己处理。而AppLifecycleListener则是在WidgetsBindingObserver.didChangeAppLifecycleState的基础上进行了封装,再配合当前lifecycleState形成更完整的生命周期链条,对于开发者来说就是使用更方便,并且API相应更直观。

以下是一个简单的使用AppLifecycleListener的示例:

dart 复制代码
late final AppLifecycleListener _listener;
late AppLifecycleState? _state;

@override
void initState() {
  super.initState();
  _state = SchedulerBinding.instance.lifecycleState;
  _listener = AppLifecycleListener(
    onShow: () => _handleTransition('show'),
    onResume: () => _handleTransition('resume'),
    onHide: () => _handleTransition('hide'),
    onInactive: () => _handleTransition('inactive'),
    onPause: () => _handleTransition('pause'),
    onDetach: () => _handleTransition('detach'),
    onRestart: () => _handleTransition('restart'),
    // 每次状态改变都会触发。上面的回调只用于特定的状态转换。
    onStateChange: _handleStateChange,
  );
}

void _handleTransition(String name) {
  print("########################## main $name");
}

总结

  1. late AppLifecycleState? _state是一个实例变量,用于存储当前应用程序的生命周期状态。在上述示例中,_state在initState()方法中被初始化为当前应用程序的生命周期状态,即SchedulerBinding.instance.lifecycleState。虽然在这个示例中没有使用_state,但是在其他的应用场景中,你可能需要使用它来记录应用程序的生命周期状态并在后续的处理中使用。
  2. AppLifecycleListener是一个完整的类,所以使用它无需使用mixin,你只需要在使用的地方创建一个AppLifecycleListener对象即可。AppLifecycleListener根据AppLifecycleState区分好了所有回调调用,调用编排更加直观。最后,AppLifecycleListener可以更方便地判断和记录整个生命周期的链条变化,因为它已经帮你封装好回调方法。
相关推荐
m0_738185821 小时前
Flutter 鸿蒙化实战:flutter_nfc_kit 适配 OpenHarmony,NFC 读写一步到位
flutter·华为·harmonyos·鸿蒙
恋猫de小郭2 小时前
KMP 又改了编译流程, Separate Compilation 禁止了 `commonMain` 的依赖穿透
android·前端·flutter
执明wa2 小时前
Android RecyclerView 实战:点击频道栏切换对应内容
android·开发语言·windows·microsoft·android studio
m0_738185822 小时前
Flutter 鸿蒙化实战:flutter_quill 适配 OpenHarmony,富文本编辑器
flutter·华为·harmonyos·鸿蒙
m0_738185822 小时前
Flutter 鸿蒙化实战:flutter_quick_video_encoder 适配 OpenHarmony,逐帧编码视频
flutter·华为·音视频·harmonyos·鸿蒙
新鲜势力呀3 小时前
PHP 定时数据同步实战:从第三方接口超时到异步同步 + 增量更新架构优化全过程
android
茶底世界之下3 小时前
为什么高精度透明图片上传到 Metal 时,必须把“拷贝像素”与“混合合成”分开
ios
老李IT笔记4 小时前
iOS 27 更新延迟只能给 1 到 90 天:两个参数怎么配,配错了会发生什么
ios·智能手机
星间都市山脉4 小时前
RecoveryUI 圆角屏安全边距配置及代码调用链
android·java·linux·windows·ubuntu
打工仔折腾 AI5 小时前
DiPlay 实测:iPhone 绕过硬件盒子直连 BYD 车机的思路拆解
android·人工智能·后端·python·gradle·iphone·ai agent 实战