Flutter生命周期管理插件an_lifecycle_hooks的使用

Flutter生命周期管理插件an_lifecycle_hooks的使用

使用

1.1 准备生命周期环境

在应用中使用 LifecycleApp 包装默认的 App,并注册路由事件变化。

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 使用 LifecycleApp 包装默认 App
    return LifecycleApp(
      child: MaterialApp(
        title: 'Lifecycle Hook Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        navigatorObservers: [
          // 使用 LifecycleNavigatorObserver.hookMode() 来注册路由事件的变化
          LifecycleNavigatorObserver.hookMode(),
        ],
        home: const MyHomePage(title: 'Lifecycle Hook Home Page'),
      ),
    );
  }
}

PageViewTabBarView 应该被替换为 LifecyclePageViewLifecycleTabBarView。你也可以将项目包装在 LifecyclePageViewItem 中。更多详情可以参考 anlifecycle

1.2 使用 useLifecycle 和 useLifecycleEffect

使用 useLifecycleuseLifecycleEffect 来处理生命周期相关的逻辑。

class HomeService {
  final Lifecycle lifecycle;
  final ValueNotifier<int> stayed = ValueNotifier<int>(0);

  HomeService(this.lifecycle) {
    // stayed ValueNotifier 绑定到生命周期,当生命周期销毁时会自动调用 [ValueNotifier.dispose]
    stayed.bindLifecycle(lifecycle);
  }

  void startTicker() {
    // 在可见的时间每秒增加1,不可见时不增加
    Stream.periodic(const Duration(seconds: 1))
        .bindLifecycle(lifecycle, repeatLastOnRestart: true)
        .listen((_) => stayed.value += 1);
  }
}

class HomeServiceDemo extends HookWidget {
  const HomeServiceDemo({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 单独使用lifecycle
    final homeService = useLifecycleEffect<HomeService>(
      factory2: HomeService.new,
      // 在首次可见时启动
      launchOnFirstResume: (_, service) => service.startTicker(),
    );
    // hooks 处理变化
    final stayed = useListenable(homeService.stayed);

    return Scaffold(
      appBar: AppBar(
        title: Text('Lifecycle Hook Demo Home Page'),
      ),
      body: Center(
        child: Text(
          'Stayed on this page for:${stayed.value} s',
        ),
      ),
    );
  }
}

1.3 使用 useLifecycleViewModelEffect 直接处理与 ViewModel 相关的功能

使用 useLifecycleViewModelEffect 来直接处理与 ViewModel 相关的功能。

class HomeViewModel with ViewModel {
  // 存放全局配置
  final AppViewModel appModel;

  // 创建一个自动管理的 ValueNotifier<int>
  late final counter = valueNotifier(0);

  // 可以从lifecycle中获取已存在的ViewModel
  HomeViewModel(Lifecycle lifecycle) : appModel = lifecycle.viewModelsByApp();

  void incrementCounter() {
    counter.value += appModel.incrementStep;
  }
}

class HomeViewModelDemo extends HookWidget {
  const HomeViewModelDemo({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 使用viewmodel
    final viewModel = useLifecycleViewModelEffect(factory2: HomeViewModel.new);

    // hooks 处理变化
    final counter = useListenable(viewModel.counter);

    return Scaffold(
      appBar: AppBar(
        title: Text('ViewModel Hook Demo Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '${counter.value}',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: const HomeFloatingButton(),
    );
  }
}

/// 模拟这是另一个widget 需要使用MyHomePage中的同一个ViewModel
class HomeFloatingButton extends HookWidget {
  const HomeFloatingButton({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 如果提前已经注册过或者确定已经存在对象则可以直接使用
    final vm = useLifecycleViewModelEffect<HomeViewModel>();
    return FloatingActionButton(
      onPressed: vm.incrementCounter,
      tooltip: 'Increment',
      child: const Icon(Icons.add),
    );
  }
}

更多关于Flutter生命周期管理插件an_lifecycle_hooks的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter生命周期管理插件an_lifecycle_hooks的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


an_lifecycle_hooks 是一个用于 Flutter 的插件,它允许你在 Flutter 应用的生命周期事件中执行自定义逻辑。这个插件可以帮助你更好地管理应用的生命周期,例如在应用进入后台或前台时执行某些操作。

安装

首先,你需要在 pubspec.yaml 文件中添加 an_lifecycle_hooks 依赖:

dependencies:
  flutter:
    sdk: flutter
  an_lifecycle_hooks: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

基本用法

an_lifecycle_hooks 提供了几个钩子函数,允许你在不同的应用生命周期事件中执行代码。以下是一些常用的生命周期事件:

  • onResume: 当应用从后台进入前台时触发。
  • onPause: 当应用从前台进入后台时触发。
  • onDetach: 当应用被销毁时触发(例如在 Android 上按下返回键退出应用)。
  • onInactive: 当应用处于非活动状态时触发(例如在 iOS 上进入多任务视图)。
  • onRestarted: 当应用从后台重新启动时触发。

示例代码

以下是一个简单的示例,展示了如何使用 an_lifecycle_hooks 来监听应用的生命周期事件:

import 'package:flutter/material.dart';
import 'package:an_lifecycle_hooks/an_lifecycle_hooks.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Lifecycle Hooks Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LifecycleDemo(),
    );
  }
}

class LifecycleDemo extends StatefulWidget {
  [@override](/user/override)
  _LifecycleDemoState createState() => _LifecycleDemoState();
}

class _LifecycleDemoState extends State<LifecycleDemo> with LifecycleHooks {
  [@override](/user/override)
  void onResume() {
    print('App resumed');
  }

  [@override](/user/override)
  void onPause() {
    print('App paused');
  }

  [@override](/user/override)
  void onDetach() {
    print('App detached');
  }

  [@override](/user/override)
  void onInactive() {
    print('App inactive');
  }

  [@override](/user/override)
  void onRestarted() {
    print('App restarted');
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Lifecycle Hooks Demo'),
      ),
      body: Center(
        child: Text('Check the console for lifecycle events'),
      ),
    );
  }
}
回到顶部