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

引言

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

在Flutter 3.13之前,我们通常使用WidgetsBindingObserverdidChangeAppLifecycleState方法来实现生命周期的监听。但是,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是一个实例变量,用于存储当前应用程序的生命周期状态。在上述示例中,_stateinitState()方法中被初始化为当前应用程序的生命周期状态,即SchedulerBinding.instance.lifecycleState。虽然在这个示例中没有使用_state,但是在其他的应用场景中,你可能需要使用它来记录应用程序的生命周期状态并在后续的处理中使用。
  2. AppLifecycleListener是一个完整的类,所以使用它无需使用mixin,你只需要在使用的地方创建一个AppLifecycleListener对象即可。AppLifecycleListener根据AppLifecycleState区分好了所有回调调用,调用编排更加直观。最后,AppLifecycleListener可以更方便地判断和记录整个生命周期的链条变化,因为它已经帮你封装好回调方法。
相关推荐
尤老师FPGA9 分钟前
petalinux修改设备树添加vdma生成linux系统
android·linux·运维
月山知了17 分钟前
linux kernel component子系统:基于rk3588 Android 14 kernel-6.1 display-subsystem代码分析
android·linux·运维
2501_920627611 小时前
Flutter 框架跨平台鸿蒙开发 - 古文学习应用
学习·flutter·harmonyos
leo_messi942 小时前
多线程(五) -- 并发工具(二) -- J.U.C并发包(八) -- CompletableFuture组合式异步编程
android·java·c语言
芙莉莲教你写代码3 小时前
Flutter 框架跨平台鸿蒙开发 - 魔术教学
flutter·华为·harmonyos
weixin_443478514 小时前
Flutter第三方常用组件包之路由管理
前端·javascript·flutter
左手厨刀右手茼蒿5 小时前
Flutter 三方库 bs58 的鸿蒙化适配指南 - 在鸿蒙系统上构建极致、高效的 Base58 数字货币与区块链数据编解码引擎
flutter·harmonyos·鸿蒙·openharmony
加农炮手Jinx5 小时前
Flutter 组件 substrate_bip39 的适配 鸿蒙Harmony 实战 - 驾驭区块链级助记词原语、实现鸿蒙端金融级 BIP39 安全私钥推导方案
flutter·harmonyos·鸿蒙·openharmony·substrate_bip39
左手厨刀右手茼蒿5 小时前
Flutter 组件 substrate_bip39 的适配 鸿蒙Harmony 实战 - 驾驭区块链级 BIP39 安全底座、实现鸿蒙端私钥派生与国密级密钥保护方案
flutter·harmonyos·鸿蒙·openharmony·substrate_bip39
加农炮手Jinx5 小时前
Flutter 三方库 fast_base58 的鸿蒙化进阶指南 - 挑战编解码吞吐量极限、助力鸿蒙端大规模区块链与分布式存储数据处理
flutter·harmonyos·鸿蒙·openharmony·fast_base58