Flutter路由监听插件route_observer_mixin的使用

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

Flutter路由监听插件route_observer_mixin的使用

Gif

RouteObserveMixin 提供了对 didPushdidPopdidPushNextdidPopNext 的简单访问,允许开发者在页面导航时执行特定逻辑。以下是具体用法:

使用方法

1. 包裹MaterialApp与RouteObserverProvider

首先,你需要将你的 MaterialApp 包裹在一个 RouteObserverProvider 中。这可以通过 MultiProvider 来实现,或者直接使用 RouteObserverProvider

void main() {
  runApp(
    MultiProvider(
      providers: [
        // 1. Wrap MaterialApp with RouteObserverProvider.
        RouteObserverProvider(),
        ChangeNotifierProvider(create: (context) => Logger())
      ],
      child: const App(),
    ),
  );

  // Of course, this is also ok.
  // I demonstrated that [MultiProvider] can be used for RouteObserverProvider👍

  /*
  runApp(
    RouteObserverProvider(
      child: App(),
    ),
  );
  */
}

2. 将RouteObserverProvider.of(context)传递给navigatorObservers

接下来,需要将 RouteObserverProvider.of(context) 传递给 MaterialAppnavigatorObservers 属性中。

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // 2. Pass RouteObserverProvider.of(context) to navigatorObservers.
      navigatorObservers: [RouteObserverProvider.of(context)],
      home: const APage(),
    );
  }
}

3. 在State中添加RouteAware和RouteObserverMixin并覆盖RouteAware方法

最后,在你想要监听路由变化的页面的 State 类中添加 with RouteAware, RouteObserverMixin 并覆盖 RouteAware 方法。

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

  @override
  _APageState createState() => _APageState();
}

// 3. Add `with RouteAware, RouteObserverMixin` to State and override RouteAware methods.
class _APageState extends State<APage> with RouteAware, RouteObserverMixin {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('A Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.of(context).push<void>(
              MaterialPageRoute(
                builder: (context) => const BPage(),
              ),
            );
          },
          child: const Text('B Page'),
        ),
      ),
    );
  }

  /// Called when the top route has been popped off, and the current route shows up.
  @override
  void didPopNext() { 
    print("Did Pop Next");
  }

  /// Called when the current route has been pushed.
  @override
  void didPush() { 
    print("Did Push");
  }

  /// Called when the current route has been popped off.
  @override
  void didPop() { 
    print("Did Pop");
  }

  /// Called when a new route has been pushed, and the current route is no longer visible.
  @override
  void didPushNext() { 
    print("Did Push Next");
  }
}

示例代码

以下是一个完整的示例demo,展示了如何使用 route_observer_mixin 插件进行路由监听:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:route_observer_mixin/route_observer_mixin.dart';

import 'log_view.dart';
import 'pages/pages.dart';

void main() {
  runApp(
    MultiProvider(
      providers: [
        // 1. Wrap MaterialApp with RouteObserverProvider.
        RouteObserverProvider(
          create: (context) => GlobalRouteObserver()..navigation.listen(print),
        ),
        ChangeNotifierProvider(create: (context) => Logger())
      ],
      child: const App(),
    ),
  );

  // Of course, this is also ok.
  // I demonstrated that [MultiProvider] can be used for RouteObserverProvider👍

  /*
  runApp(
    RouteObserverProvider(
      child: const App(),
    ),
  );
  */
}

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: MaterialApp(
            // 2. Pass RouteObserverProvider.of(context) to navigatorObservers.
            navigatorObservers: [RouteObserverProvider.of(context)],
            home: const APage(),
          ),
        ),
        const SizedBox(
          height: 300,
          child: LogView(),
        ),
      ],
    );
  }
}

通过以上步骤,你可以轻松地在Flutter应用中使用 route_observer_mixin 插件来监听路由变化,并根据需要执行相应的操作。


更多关于Flutter路由监听插件route_observer_mixin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter路由监听插件route_observer_mixin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter中使用route_observer_mixin插件进行路由监听的代码示例。route_observer_mixin是一个可以帮助你监听路由变化的Flutter插件。虽然这个插件可能不是官方维护的(因为Flutter本身有强大的路由管理功能),但假设它提供了一个类似的功能,我们可以通过下面的代码展示如何使用它。

首先,你需要确保在你的pubspec.yaml文件中添加了该依赖项(假设该插件的名为route_observer_mixin,并且已经发布在pub.dev上):

dependencies:
  flutter:
    sdk: flutter
  route_observer_mixin: ^x.y.z  # 替换为实际版本号

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

接下来,我们创建一个Flutter应用并集成route_observer_mixin

1. 创建一个Flutter应用

假设你已经有一个Flutter项目,如果没有,你可以通过flutter create my_app创建一个。

2. 配置路由

假设你使用的是flutter/material提供的路由管理,我们可以这样配置路由:

import 'package:flutter/material.dart';
import 'package:route_observer_mixin/route_observer_mixin.dart'; // 假设这是插件的导入路径

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

class MyApp extends StatelessWidget with RouteAware {
  final navigatorKey = GlobalKey<NavigatorState>();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey,
      onGenerateRoute: (RouteSettings settings) {
        // 简单的路由配置示例
        switch (settings.name) {
          case '/':
            return MaterialPageRoute(builder: (context) => HomeScreen());
          case '/second':
            return MaterialPageRoute(builder: (context) => SecondScreen());
          default:
            return MaterialPageRoute(builder: (context) => Scaffold(body: Center(child: Text('Unknown route'))));
        }
      },
      home: HomeScreen(),
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouteObserver<PageRoute>().subscribe(this, ModalRoute.of(context)!);
  }

  @override
  void dispose() {
    RouteObserver<PageRoute>().unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {
    print("Route pushed");
  }

  @override
  void didPop() {
    print("Route popped");
  }

  @override
  void didPopNext() {
    print("Route popped next");
  }

  @override
  void didReplace({Object? newRoute, Object? oldRoute}) {
    print("Route replaced from $oldRoute to $newRoute");
  }
}

3. 创建屏幕组件

创建两个简单的屏幕组件,HomeScreenSecondScreen

import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.of(context).pushNamed('/second');
          },
          child: Text('Go to Second Screen'),
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: Text('Go back'),
        ),
      ),
    );
  }
}

4. 运行应用

现在,你可以运行你的Flutter应用,并观察控制台输出,当你导航到不同的屏幕时,你应该会看到路由变化的打印信息。

请注意,route_observer_mixin插件的具体实现和API可能有所不同,这里的代码是基于假设的API进行演示的。如果route_observer_mixin实际上不存在或API不同,你可能需要参考该插件的实际文档或源代码进行调整。Flutter本身提供的NavigatorObserver类也是一个强大的工具,可以用来监听路由变化,而不需要额外的插件。

回到顶部