Flutter路由生命周期管理插件route_lifecycle的使用

Flutter路由生命周期管理插件route_lifecycle的使用

route_lifecycle 是一种新的管理路由生命周期的方法。

安装

添加到pubspec.yaml文件

最新版本是:

dependencies:
  route_lifecycle: $latest_version

在Dart代码中导入

import 'package:route_lifecycle/route_lifecycle.dart';

使用

配置navigatorObservers

MaterialApp中添加navigatorObservers来监听路由生命周期事件。

MaterialApp(
  navigatorObservers: [
    ...
    RouteMixin.getRouteLifecycleObserver(),
  ],
);

使用RouteMixin<T>

在需要管理路由生命周期的类中使用RouteMixin<T>

class _HomePageState extends State<HomePage> with RouteMixin<HomePage> {
  [@override](/user/override)
  String getRouteName() {
    return "/main";
  }

  [@override](/user/override)
  void init() {
    super.init();
  }

  [@override](/user/override)
  void resume() {
    super.resume();
  }

  [@override](/user/override)
  void stop() {
    super.stop();
  }

  [@override](/user/override)
  void inactive() {
    super.inactive();
  }
}

示例代码

以下是一个完整的示例代码,展示了如何使用route_lifecycle插件来管理路由生命周期。

main.dart

/// [@author](/user/author) newtab on 2021/5/7

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:route_lifecycle/route_lifecycle.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        "/main": (context) => HomePage(),
        "/a2": (context) => HomePage2(),
        "/a3": (context) => Home3Page(),
      },
      initialRoute: "/main",
      navigatorObservers: [
        RouteMixin.getRouteLifecycleObserver(),
      ],
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  [@override](/user/override)
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with RouteMixin<HomePage> {
  [@override](/user/override)
  void initState() {
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: InkWell(
        onTap: () {
          Navigator.of(context).pushNamed("/a2");
        },
        child: Container(
          child: Center(
            child: Text("11111111111"),
          ),
        ),
      ),
    );
  }

  [@override](/user/override)
  String getRouteName() {
    return "/main";
  }

  [@override](/user/override)
  void init() {
    super.init();
  }

  [@override](/user/override)
  void resume() {
    super.resume();
  }

  [@override](/user/override)
  void stop() {
    super.stop();
  }

  [@override](/user/override)
  void inactive() {
    super.inactive();
  }
}

class HomePage2 extends StatefulWidget {
  const HomePage2({Key? key}) : super(key: key);

  [@override](/user/override)
  _HomePage2State createState() => _HomePage2State();
}

class _HomePage2State extends State<HomePage2> with RouteMixin<HomePage2> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: InkWell(
        onTap: () {
          Navigator.of(context).pushNamed("/a3");
        },
        child: Container(
          child: Center(
            child: Text("2222222222222222"),
          ),
        ),
      ),
    );
  }

  [@override](/user/override)
  void init() {
    super.init();
    print(".....${getRouteName()} init");
  }

  [@override](/user/override)
  String getRouteName() {
    return "/a2";
  }

  [@override](/user/override)
  void stop() {
    super.stop();
    print(".....${getRouteName()} stoped");
  }

  [@override](/user/override)
  void resume() {
    print(".....${getRouteName()} resumed");
    super.resume();
  }

  [@override](/user/override)
  void inactive() {
    print(".....${getRouteName()} inactive");
    super.inactive();
  }
}

class Home3Page extends StatefulWidget {
  const Home3Page({Key? key}) : super(key: key);

  [@override](/user/override)
  _Home3PageState createState() => _Home3PageState();
}

class _Home3PageState extends State<Home3Page> with RouteMixin<Home3Page> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: InkWell(
        onTap: () {
          Navigator.of(context)
              .popUntil((route) => route.settings.name == "/main");
        },
        child: Container(
          child: Center(
            child: Text("33333333"),
          ),
        ),
      ),
    );
  }

  [@override](/user/override)
  String getRouteName() {
    return "/a3";
  }

  [@override](/user/override)
  void resume() {
    print(".....${getRouteName()} resumed");
    super.resume();
  }

  [@override](/user/override)
  void stop() {
    print(".....${getRouteName()} stoped");
    super.stop();
  }

  [@override](/user/override)
  void inactive() {
    print(".....${getRouteName()} inactive");
    super.inactive();
  }

  [@override](/user/override)
  void init() {
    super.init();
    print(".....${getRouteName()} init");
  }
}

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

1 回复

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


route_lifecycle 是一个用于 Flutter 的路由生命周期管理插件,它可以帮助开发者监听和响应 Flutter 路由的生命周期事件,例如路由的进入、退出等。这对于需要在路由切换时执行特定操作的场景非常有用,例如在页面进入时加载数据,在页面退出时保存数据或释放资源。

安装

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

dependencies:
  flutter:
    sdk: flutter
  route_lifecycle: ^0.1.0  # 请使用最新版本

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

基本用法

route_lifecycle 插件提供了 RouteLifecycleObserver 类,你可以将其添加到 NavigatorObservers 中,从而监听路由的生命周期事件。

1. 创建 RouteLifecycleObserver

你可以创建一个自定义的 RouteLifecycleObserver 来监听路由的生命周期事件:

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

class MyRouteObserver extends RouteLifecycleObserver {
  [@override](/user/override)
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    print('Route pushed: ${route.settings.name}');
  }

  [@override](/user/override)
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    print('Route popped: ${route.settings.name}');
  }

  [@override](/user/override)
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didRemove(route, previousRoute);
    print('Route removed: ${route.settings.name}');
  }

  [@override](/user/override)
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    print('Route replaced: ${newRoute?.settings.name}');
  }
}

2. 将 RouteLifecycleObserver 添加到 NavigatorObservers

在你的 MaterialAppCupertinoApp 中,将 MyRouteObserver 添加到 navigatorObservers 中:

import 'package:flutter/material.dart';
import 'my_route_observer.dart'; // 导入自定义的 RouteLifecycleObserver

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

class MyApp extends StatelessWidget {
  final MyRouteObserver _routeObserver = MyRouteObserver();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Route Lifecycle Demo',
      navigatorObservers: [_routeObserver],
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondPage()),
            );
          },
          child: Text('Go to Second Page'),
        ),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Page')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go back'),
        ),
      ),
    );
  }
}
回到顶部