Flutter路由管理插件better_router的使用

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

Flutter路由管理插件better_router的使用

特性

  • 静态路由
  • 动态路由
  • 通配符匹配所有

开始使用

首先,在你的项目中添加 better_router 插件:

flutter pub add better_router

使用方法

示例代码

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

// 定义书籍类
class Book {
  final String id;
  final String name;
  final String author;

  const Book({required this.id, required this.name, required this.author});
}

void main() {
  // 定义一些书籍数据
  final books = [
    const Book(id: '3160', name: '奥德赛', author: '荷马'),
    const Book(id: '8795', name: '神曲', author: '但丁'),
  ];

  // 定义路由表
  final betterRoutes = BetterRouter(routes: {
    '/': DefaultPageRouteBuilder((context) => Column(children: [
          Text('首页'),
          TextButton(
              onPressed: () => Navigator.pushNamed(context, "/books"),
              child: Text("书籍")),
          TextButton(
            onPressed: () =>
                Navigator.pushNamed(context, "/this_page_does_not_exists"),
            child: Text("前往不存在的页面"),
          ),
          TextButton(
            onPressed: () =>
                Navigator.pushNamed(context, "/custom_route_transition"),
            child: Text("前往自定义过渡效果页面"),
          )
        ])),
    '/home': DefaultPageRouteBuilder((_) => Text('主页')),
    '/books': DefaultPageRouteBuilder((context) => Column(children: [
          for (var i = 0; i < books.length; i++)
            TextButton(
                onPressed: () =>
                    Navigator.pushNamed(context, "/books/${books[i].id}"),
                child: Text(books[i].name))
        ])),
    r"\/books\/(?<id>.+)": DefaultPageRouteBuilder((context) {
      final params = RouteParams.of(context);

      return Column(
        children: [Text('书籍详情页'), Text("书籍ID: ${params['id']}")],
      );
    }),
    '/custom_route_transition': (RouteSettings settings) => PageRouteBuilder(
      pageBuilder: (context, animation, secondaryAnimation) =>
          Text("过渡效果"),
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        var begin = Offset(0.0, 1.0);
        var end = Offset.zero;
        var tween = Tween(begin: begin, end: end);
        var offsetAnimation = animation.drive(tween);

        return SlideTransition(
          position: offsetAnimation,
          child: child,
        );
      },
    ),
    '*matchAll': PageRouteBuilder((_) => Text('找不到页面')),
  });

  // 运行应用
  runApp(MaterialApp(onGenerateRoute: betterRoutes));
}

代码解释

  1. 定义书籍类

    class Book {
      final String id;
      final String name;
      final String author;
    
      const Book({required this.id, required this.name, required this.author});
    }
    

    这里定义了一个简单的 Book 类来表示书籍信息。

  2. 定义路由表

    final betterRoutes = BetterRouter(routes: {
      '/': DefaultPageRouteBuilder((context) => Column(children: [
            Text('首页'),
            TextButton(
                onPressed: () => Navigator.pushNamed(context, "/books"),
                child: Text("书籍")),
            TextButton(
              onPressed: () =>
                  Navigator.pushNamed(context, "/this_page_does_not_exists"),
              child: Text("前往不存在的页面"),
            ),
            TextButton(
              onPressed: () =>
                  Navigator.pushNamed(context, "/custom_route_transition"),
              child: Text("前往自定义过渡效果页面"),
            )
          ])),
      '/home': DefaultPageRouteBuilder((_) => Text('主页')),
      '/books': DefaultPageRouteBuilder((context) => Column(children: [
            for (var i = 0; i < books.length; i++)
              TextButton(
                  onPressed: () =>
                      Navigator.pushNamed(context, "/books/${books[i].id}"),
                  child: Text(books[i].name))
          ])),
      r"\/books\/(?<id>.+)": DefaultPageRouteBuilder((context) {
        final params = RouteParams.of(context);
    
        return Column(
          children: [Text('书籍详情页'), Text("书籍ID: ${params['id']}")],
        );
      }),
      '/custom_route_transition': (RouteSettings settings) => PageRouteBuilder(
        pageBuilder: (context, animation, secondaryAnimation) =>
            Text("过渡效果"),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          var begin = Offset(0.0, 1.0);
          var end = Offset.zero;
          var tween = Tween(begin: begin, end: end);
          var offsetAnimation = animation.drive(tween);
    
          return SlideTransition(
            position: offsetAnimation,
            child: child,
          );
        },
      ),
      '*matchAll': PageRouteBuilder((_) => Text('找不到页面')),
    });
    
    • / 路由:根路径,包含三个按钮,分别跳转到书籍列表页、不存在的页面和自定义过渡效果页面。
    • /home 路由:主页,仅显示文本 “主页”。
    • /books 路由:书籍列表页,动态生成按钮,每个按钮点击后跳转到对应的书籍详情页。
    • r"\/books\/(?<id>.+)" 路由:匹配书籍详情页,通过正则表达式捕获书籍ID。
    • /custom_route_transition 路由:自定义过渡效果页,使用滑动过渡动画。
    • *matchAll 路由:通配符路由,用于处理未匹配的路由。
  3. 运行应用

    runApp(MaterialApp(onGenerateRoute: betterRoutes));
    

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用better_router插件进行路由管理的代码示例。better_router是一个强大的路由管理插件,它允许你以声明式的方式定义应用的路由。

首先,确保你的pubspec.yaml文件中包含了better_router依赖:

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

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

步骤 1: 定义路由配置

创建一个router_config.dart文件来定义你的路由配置。

import 'package:better_router/better_router.dart';
import 'package:flutter/material.dart';
import 'screens/home_screen.dart';
import 'screens/detail_screen.dart';

class MyRouter extends BetterRouter {
  @override
  List<BetterRoute> get routes => [
    BetterRoute(
      path: '/',
      builder: (_, __) => HomeScreen(),
    ),
    BetterRoute(
      path: '/detail/:id',
      builder: (_, args) => DetailScreen(id: args['id'] as String),
    ),
  ];
}

步骤 2: 创建屏幕

创建screens/home_screen.dartscreens/detail_screen.dart文件。

home_screen.dart

import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // 导航到详情页面,传递一个id参数
            BetterRouter.of(context).navigateTo('/detail/123');
          },
          child: Text('Go to Detail'),
        ),
      ),
    );
  }
}

detail_screen.dart

import 'package:flutter/material.dart';

class DetailScreen extends StatelessWidget {
  final String id;

  DetailScreen({required this.id});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Detail Screen')),
      body: Center(
        child: Text('Detail for ID: $id'),
      ),
    );
  }
}

步骤 3: 在主应用中集成路由

在你的main.dart文件中,集成better_router

import 'package:flutter/material.dart';
import 'package:better_router/better_router.dart';
import 'router_config.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerDelegate: MyRouter.delegate(),
      routeInformationParser: MyRouter.routeInformationParser(),
      title: 'Flutter Demo',
    );
  }
}

总结

以上代码展示了如何使用better_router在Flutter应用中实现路由管理。通过定义路由配置、创建屏幕组件并在主应用中集成路由,你可以轻松地在应用的不同屏幕之间进行导航。better_router的声明式路由定义方式使得路由管理更加清晰和易于维护。

回到顶部