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

发布于 1周前 作者 yuanlaile 来自 Flutter

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

AnLifecycle借鉴了AndroidX的生命周期实现,使Flutter开发者能够在需要的地方感知当前上下文的生命周期状态。本文将详细介绍如何使用anlifecycle插件来管理Flutter应用的生命周期。

生命周期事件和状态

生命周期事件

enum LifecycleEvent {
  create,
  start,
  resume,
  pause,
  stop,
  destroy,
}

生命周期状态

enum LifecycleState {
  destroyed,
  initialized,
  created,
  started,
  resumed,
}

使用方法

1.1 包装应用并注册观察者

首先,使用LifecycleApp包装默认的应用,并在MaterialApp中注册LifecycleNavigatorObserver.hookMode()以监听路由事件变化。

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return LifecycleApp(
      child: MaterialApp(
        navigatorObservers: [
          LifecycleNavigatorObserver.hookMode(),
        ],
        routes: {
          '/': (context) => const MyHomePage(title: 'LifecycleApp'),
          '/first': (_) => const FistPage(),
          '/second': (_) => const SecondPage(),
          '/pageView': (_) => const PageViewExample(),
        },
      ),
    );
  }
}

1.2 观察PageViewTabBarView中的项目生命周期

如果需要观察PageViewTabBarView中的项目生命周期,可以使用LifecyclePageViewLifecycleTabBarView

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return LifecyclePageView(
      children: [
        for (int i = 0; i < 9; i++) ItemView(index: i),
      ],
    );
  }
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return LifecycleTabBarView(
      children: [
        for (int i = 0; i < 9; i++) ItemView(index: i),
      ],
    );
  }
}

1.3 利用完整的生命周期状态和事件

可以通过混入LifecycleRegistryStateMixin来利用完整的生命周期状态和事件。

class FistPage extends StatefulWidget {
  const FistPage({super.key});

  [@override](/user/override)
  State<FistPage> createState() => _FistPageState();
}

class _FistPageState extends State<FistPage>
    with LifecycleRegistryStateMixin, LifecycleEventPrinter {
  [@override](/user/override)
  void initState() {
    super.initState();

    addLifecycleObserver(LifecycleObserver.stateChange((state) {
      print('LifecycleStatePrinter $runtimeType $state');
    }));

    addLifecycleObserver(LifecycleObserver.eventAny((event) {
      print('LifecycleEventPrinter $runtimeType $event');
    }));
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fist Page'),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            GestureDetector(
              onTap: () {
                Navigator.of(context).pushNamed('/second');
              },
              child: const Text('Tap go second page'),
            ),
            const Padding(padding: EdgeInsets.only(top: 12)),
            GestureDetector(
              onTap: () {
                showDialog(
                    context: context,
                    builder: (context) => const Text('dialog'));
              },
              child: const Text('Tap show Dialog'),
            ),
          ],
        ),
      ),
    );
  }
}

示例代码

以下是一个完整的示例代码,展示了如何使用anlifecycle插件。

import 'package:anlifecycle/lifecycle.dart';
import 'package:flutter/material.dart';

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

final routes = <String, WidgetBuilder>{
  '/': (context) => const MyHomePage(title: 'LifecycleApp'),
  '/first': (_) => const FistPage(),
  '/second': (_) => const SecondPage(),
  '/pageView': (_) => const PageViewExample(),
};

mixin LifecycleEventPrinter<W extends StatefulWidget> on LifecycleRegistryStateMixin<W> {
  String get otherTag => '';

  [@override](/user/override)
  void initState() {
    super.initState();
    final printer = LifecycleObserver.eventAny((event) {
      print('LifecycleEventPrinter $runtimeType $otherTag $event');
    });
    addLifecycleObserver(printer);
  }
}

mixin LifecycleStatePrinter<W extends StatefulWidget> on LifecycleRegistryStateMixin<W> {
  String get otherTag => '';

  [@override](/user/override)
  void initState() {
    super.initState();
    final printer = LifecycleObserver.stateChange((state) {
      print('LifecycleStatePrinter $runtimeType $otherTag $state');
    });
    addLifecycleObserver(printer);
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with LifecycleRegistryStateMixin, LifecycleEventPrinter {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: GestureDetector(
          onTap: () {
            Navigator.of(context).pushNamed('/first');
          },
          child: const Text('Tap go first page'),
        ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  const SecondPage({super.key});

  [@override](/user/override)
  State<SecondPage> createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage>
    with LifecycleRegistryStateMixin, LifecycleEventPrinter {
  [@override](/user/override)
  Widget build(BuildContext context) {
    print('SecondPage build');
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Page'),
      ),
      body: const Center(
        child: Text('Second'),
      ),
    );
  }
}

class PageViewExample extends StatefulWidget {
  const PageViewExample({super.key});

  [@override](/user/override)
  State<PageViewExample> createState() => _PageViewExampleState();
}

class _PageViewExampleState extends State<PageViewExample>
    with LifecycleRegistryStateMixin, LifecycleEventPrinter {
  final PageController _pageController = PageController(initialPage: 2);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('PageViewExample'),
      ),
      body: LifecyclePageView(
        controller: _pageController,
        children: [
          for (int i = 0; i < 9; i++) ItemView(index: i),
        ],
      ),
    );
  }
}

class ItemView extends StatefulWidget {
  final int index;

  const ItemView({super.key, required this.index});

  [@override](/user/override)
  State<ItemView> createState() => _ItemViewState();
}

class _ItemViewState extends State<ItemView>
    with LifecycleRegistryStateMixin, LifecycleEventPrinter {
  [@override](/user/override)
  String get otherTag => 'Page index ${widget.index}';

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Container(
      color: Colors.green[(widget.index + 1) * 100],
      child: Center(
        child: Text('Page index ${widget.index}'),
      ),
    );
  }
}

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

1 回复

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


在Flutter应用中,管理应用的生命周期对于执行初始化、资源清理、状态保存等操作至关重要。flutter_lifecycle 插件可以帮助开发者监听 Android 和 iOS 上的应用生命周期事件。下面是一个使用 flutter_lifecycle 插件的代码案例,展示如何管理 Flutter 应用的生命周期。

首先,确保你已经在 pubspec.yaml 文件中添加了 flutter_lifecycle 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_lifecycle: ^0.7.0  # 请检查最新版本号并替换

然后,运行 flutter pub get 来获取依赖。

接下来,在你的 Flutter 应用中实现生命周期管理。以下是一个完整的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Lifecycle Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LifecycleAwareWidget(),
    );
  }
}

class LifecycleAwareWidget extends StatefulWidget {
  @override
  _LifecycleAwareWidgetState createState() => _LifecycleAwareWidgetState();
}

class _LifecycleAwareWidgetState extends State<LifecycleAwareWidget> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
    print('App initialized');
  }

  @override
  void dispose() {
    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
    print('App disposed');
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print('App is resumed');
        break;
      case AppLifecycleState.inactive:
        print('App is inactive');
        break;
      case AppLifecycleState.paused:
        print('App is paused');
        break;
      case AppLifecycleState.detached:
        print('App is detached from the engine');
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Lifecycle Demo'),
      ),
      body: Center(
        child: Text('Check the console for lifecycle events'),
      ),
    );
  }
}

在这个示例中,我们创建了一个 LifecycleAwareWidget,它继承自 StatefulWidget 并混合了 WidgetsBindingObserverWidgetsBindingObserver 提供了监听应用生命周期事件的能力。

  • initState 方法中,我们通过 WidgetsBinding.instance!.addObserver(this) 注册为观察者,并在控制台打印 “App initialized”。
  • dispose 方法中,我们通过 WidgetsBinding.instance!.removeObserver(this) 取消注册观察者,并在控制台打印 “App disposed”。
  • didChangeAppLifecycleState 方法会在应用生命周期状态改变时被调用。我们根据传入的状态值在控制台打印相应的信息。

这个示例展示了如何使用 flutter_lifecycle(尽管在这个特定例子中,我们实际上并没有直接使用 flutter_lifecycle 包,因为 Flutter 框架自带的 WidgetsBindingObserver 已经提供了所需的功能。不过,flutter_lifecycle 在某些高级用例中可能提供额外的功能或简化接口)。如果你的需求超出了 WidgetsBindingObserver 的范围,可以查看 flutter_lifecycle 的文档以了解更多高级用法。

回到顶部