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 回调还简化了在退出可取消的情况下处理退出的过程。

相关推荐
To_OC7 小时前
别再串行写 await 了,Promise.all 才是并行请求的正确打开方式
前端·javascript·promise
vipbic8 小时前
中后台越做越乱后,我用插件化把它救回来了
前端·vue.js
Hyyy8 小时前
Computer Use 适合做什么,不适合做什么——一次真实使用后的思考
前端
小和尚同志8 小时前
前端 AI 单元测试思考与落地
前端·人工智能·aigc
invicinble9 小时前
c端系统,其实更像一个信息展示平台
前端
李姆斯10 小时前
管理是否可以被完全量化
前端·产品经理·团队管理
名字还没想好☜11 小时前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js
广州灵眸科技有限公司11 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) INI文件操作
java·前端·javascript·网络·人工智能
心中有国也有家11 小时前
AtomGit Flutter 鸿蒙客户端:ModalBottomSheet 实战
android·javascript·学习·flutter·华为·harmonyos
kaiking_g11 小时前
vue项目中,静态导入 vs 动态导入 详解
前端·javascript·vue.js