Flutter 中监听应用程序生命周期事件的新方法

Flutter 3.13 引入了许多新功能和改进。其中之一是一个名为 AppLifecycleListener 的新类,它允许您监听 Flutter 应用程序的生命周期事件。与以前监听应用程序生命周期事件的方式相比,这是一个改进。在本文中,我将比较监听应用生命周期事件的新旧方法,并向您展示如何使用新的 AppLifecycleListener 类。

Flutter 3.13 之前

在 Flutter 3.13 之前,您可以使用 WidgetsBindingObserver mixin 监听应用生命周期事件。为此,必须将 WidgetsBindingObserver mixin 添加到您的 State 类中并重写 didChangeAppLifecycleState 方法。在 didChangeAppLifecycleState 方法中,您可以使用提供的状态 (AppLifecycleState) 值侦听应用生命周期事件。

scss 复制代码
class AppLifecyclePageOld extends StatefulWidget {
  const AppLifecyclePageOld({super.key});
  @override
  State<AppLifecyclePageOld> createState() => _AppLifecyclePageOldState();
}

class _AppLifecyclePageOldState extends State<AppLifecyclePageOld>
    // Use the WidgetsBindingObserver mixin
    with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    // Register your State class as a binding observer
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    // Unregister your State class as a binding observer
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  // Override the didChangeAppLifecycleState method and
  // listen to the app lifecycle state changes
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.detached:
        _onDetached();
      case AppLifecycleState.resumed:
        _onResumed();
      case AppLifecycleState.inactive:
        _onInactive();
      case AppLifecycleState.hidden:
        _onHidden();
      case AppLifecycleState.paused:
        _onPaused();
    }
  }

  void _onDetached() => print('detached');
  void _onResumed() => print('resumed');
  void _onInactive() => print('inactive');
  void _onHidden() => print('hidden');
  void _onPaused() => print('paused');

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Placeholder(),
    );
  }
}

让我们看看如何使用新的 AppLifecycleListener 类监听应用生命周期事件。

顺便说一句,"老"监听应用程序生命周期事件的方式仍然可用。事实上,AppLifecycleListener 在底层使用了WidgetsBindingObserver mixin。

Flutter 3.13 (含)之后

AppLifecycleListener 类是一种侦听应用生命周期事件的新方法。

您可以使用它来监听应用程序生命周期事件,而无需直接使用 WidgetsBindingObserver mixin。为此,创建 AppLifecycleListener 类的实例并传递您想要侦听的所有回调。

scss 复制代码
class AppLifecyclePage extends StatefulWidget {
  const AppLifecyclePage({super.key});
  @override
  State<AppLifecyclePage> createState() => _AppLifecyclePageState();
}

class _AppLifecyclePageState extends State<AppLifecyclePage> {
  late final AppLifecycleListener _listener;
  @override
  void initState() {
    super.initState();
    // Initialize the AppLifecycleListener class and pass callbacks
    _listener = AppLifecycleListener(
      onStateChange: _onStateChanged,
    );
  }

  @override
  void dispose() {
    // Do not forget to dispose the listener
    _listener.dispose();
    super.dispose();
  }

  // Listen to the app lifecycle state changes
  void _onStateChanged(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.detached:
        _onDetached();
      case AppLifecycleState.resumed:
        _onResumed();
      case AppLifecycleState.inactive:
        _onInactive();
      case AppLifecycleState.hidden:
        _onHidden();
      case AppLifecycleState.paused:
        _onPaused();
    }
  }

  void _onDetached() => print('detached');
  void _onResumed() => print('resumed');
  void _onInactive() => print('inactive');
  void _onHidden() => print('hidden');
  void _onPaused() => print('paused');

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Placeholder(),
    );
  }
}

区别

俩者版本监听应用程序生命周期事件的方式非常相似。不过,为了了解 AppLifecycleListener 类的主要好处,让我们看一下 Flutter 应用生命周期的状态机图:

此图显示了 Flutter 应用程序的所有可能状态。箭头显示状态之间可能的转换。当重写 didChangeAppLifecycleState 方法时,您只能监听实际的状态变化,例如当您的应用进入 resumed 状态时。但是,您无法收听状态之间的转换,例如您的应用是否从inactivedetached 状态进入 resumed 状态。现在,AppLifecycleListener 类允许您监听状态之间的转换:

scss 复制代码
class AppLifecyclePage extends StatefulWidget {
  const AppLifecyclePage({super.key});
  @override
  State<AppLifecyclePage> createState() => _AppLifecyclePageState();
}

class _AppLifecyclePageState extends State<AppLifecyclePage> {
  late final AppLifecycleListener _listener;

  @override
  void initState() {
    super.initState();
    // Pass all the callbacks for the transitions you want to listen to
    _listener = AppLifecycleListener(
      onDetach: _onDetach,
      onHide: _onHide,
      onInactive: _onInactive,
      onPause: _onPause,
      onRestart: _onRestart,
      onResume: _onResume,
      onShow: _onShow,
      onStateChange: _onStateChanged,
    );
  }

  @override
  void dispose() {
    _listener.dispose();
    super.dispose();
  }

  void _onDetach() => print('onDetach');
  void _onHide() => print('onHide');
  void _onInactive() => print('onInactive');
  void _onPause() => print('onPause');
  void _onRestart() => print('onRestart');
  void _onResume() => print('onResume');
  void _onShow() => print('onShow');
  void _onStateChanged(AppLifecycleState state) {
    // Track state changes
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Placeholder(),
    );
  }
}

这是AppLifecycleListener 类的主要优点。它允许您监听应用程序生命周期状态之间的转换,并仅针对您感兴趣的转换执行必要的代码。

onExitRequested回调

AppLifecycleListener 类还有一个名为 onExitRequested 的回调。此回调用于询问应用程序是否允许在退出可取消的情况下退出应用程序。例如,它可用于 MacOS 应用程序,其中用户在存在未保存的更改时尝试关闭应用程序:要取消退出,您需要从onExitRequested回调中返回 AppExitResponse.cancel。否则,返回AppExitResponse.exit则是允许应用程序退出。

less 复制代码
class AppLifecyclePage extends StatefulWidget {
  const AppLifecyclePage({super.key});
  @override
  State<AppLifecyclePage> createState() => _AppLifecyclePageState();
}

class _AppLifecyclePageState extends State<AppLifecyclePage> {
  late final AppLifecycleListener _listener;
  @override
  void initState() {
    super.initState();
    _listener = AppLifecycleListener(
      // Handle the onExitRequested callback
      onExitRequested: _onExitRequested,
    );
  }

  @override
  void dispose() {
    _listener.dispose();
    super.dispose();
  }

  // Ask the user if they want to exit the app. If the user
  // cancels the exit, return AppExitResponse.cancel. Otherwise,
  // return AppExitResponse.exit.
  Future<AppExitResponse> _onExitRequested() async {
    final response = await showDialog<AppExitResponse>(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog.adaptive(
        title: const Text('Are you sure you want to quit this app?'),
        content: const Text('All unsaved progress will be lost.'),
        actions: [
          TextButton(
            child: const Text('Cancel'),
            onPressed: () {
              Navigator.of(context).pop(AppExitResponse.cancel);
            },
          ),
          TextButton(
            child: const Text('Ok'),
            onPressed: () {
              Navigator.of(context).pop(AppExitResponse.exit);
            },
          ),
        ],
      ),
    );
    return response ?? AppExitResponse.exit;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('App Lifecycle Demo'),
      ),
      body: Center(
        child: Text(
          '👋',
          style: Theme.of(context).textTheme.displayLarge,
        ),
      ),
    );
  }
}

结论

AppLifecycleListener 类是一种监听应用生命周期状态的新方法,更重要的是,监听它们之间的转换。此外,onExitRequested 回调还简化了在退出可取消的情况下处理退出的过程。

相关推荐
无奈何杨36 分钟前
CoolGuard增加枚举字段支持,条件编辑优化,展望指标取值不同
前端·后端
掘金安东尼38 分钟前
工具过多:如何管理前端工具泛滥?
前端
江城开朗的豌豆1 小时前
从生命周期到useEffect:我的React函数组件进化之旅
前端·javascript·react.js
brzhang1 小时前
当AI接管80%的执行,你“不可替代”的价值,藏在这20%里
前端·后端·架构
江城开朗的豌豆1 小时前
React组件传值:轻松掌握React组件通信秘籍
前端·javascript·react.js
Sailing1 小时前
别再放任用户乱填 IP 了!一套前端 IP 与 CIDR 校验的高效方案
前端·javascript·面试
程序员爱钓鱼4 小时前
Go语言实战案例 — 项目实战篇:简易博客系统(支持评论)
前端·后端·go
excel11 小时前
ES6 中函数的双重调用方式:fn() 与 fn\...``
前端
可乐爱宅着11 小时前
全栈框架next.js入手指南
前端·next.js
你的人类朋友13 小时前
什么是API签名?
前端·后端·安全