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可以更方便地判断和记录整个生命周期的链条变化,因为它已经帮你封装好回调方法。
相关推荐
hunterandroid7 分钟前
[Android 从零到一] Retrofit 请求取消与生命周期绑定:从 Call.cancel 到协程可取消设计
android
爱跑马的程序员11 分钟前
安卓专有的通信子系统-Binder IPC
android·binder·ipc·安卓间通信机制
ue星空43 分钟前
【安卓逆向】为什么用Frida?
android
小驰行动派1 小时前
Camx架构全景图:从V4L2到Pipeline的完整拆解
android·camera·android camera
hunterandroid2 小时前
[Android 从零到一] Custom View 触摸反馈与手势冲突解决
android
coderSong25683 小时前
Android | 四大组件之 BroadcastReceiver(广播接收器)
android
qziovv4 小时前
前端转flutter——项目架构、初始化
前端·flutter
爱笑鱼6 小时前
Android 系统启动机制(二):init.rc 不是普通脚本,service、action 和 property 怎样驱动启动?
android
新鲜势力呀6 小时前
深入理解 Elliot CUDA 编程核心:PHP 实现 CUDA 并行计算思想与实践
android·开发语言·php
2501_916007476 小时前
申请 iOS 推送证书并配置 APNs 群发推送教程
android·ios·小程序·https·uni-app·iphone·webview