【Flutter】- go_router路由

文章目录


知识回顾

前言

go_router 是一个 Flutter 的第三方路由插件,相比 Flutter 自带的路由,go_router 更加灵活,而且简单易用。在 App 应用中,如果你想自己控制路由的定义和管理方式,那么它将十分有用。同时,对于 Web 应用来说,go_router 也提供了很好的支持。 使用 go_router 后,你可以定义 URL 的格式,使用 URL 跳转,处理深度链接以及其他一系列的导航相关的应用场景。

源码分析

1. 初始化

dart 复制代码
import 'package:enjoy_plus/pages/house/index.dart';
import 'package:enjoy_plus/pages/login/index.dart';
import 'package:enjoy_plus/pages/notice/index.dart';
import 'package:enjoy_plus/pages/profile/index.dart';
import 'package:enjoy_plus/pages/tab_bar_page.dart';
import 'package:enjoy_plus/utils/TokenUtil.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

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

/// 自定义go_router configuration
final GoRouter _goRouter = GoRouter(
  observers: [
    // Add your navigator observers
    MyNavigatorObserver(),
  ],
  routes: <RouteBase>[
    GoRoute(
      path: '/',
      builder: (context, state) => const TabBarPage(),
      redirect: (context, state) {},

      // 全局跳转拦截
      routes: <RouteBase>[
        GoRoute(
          path: 'detail/:id',
          builder: (context, state) {
            final id = state.pathParameters['id'];
            return NoticeDetail(
              id: id.toString(),
            );
          },
          // pageBuilder: (context, state) {
          //   return CustomTransitionPage(
          //     key: state.pageKey,
          //     transitionsBuilder: (context, animation, secondaryAnimation, child) {
          //       // Change the opacity of the screen using a Curve based on the the animation's value
          //       return FadeTransition(
          //         opacity:
          //         CurveTween(curve: Curves.easeInOutCirc).animate(animation),
          //         child: child,
          //       );
          //     },
          //     child: Container(),
          //   );
          // },
        ),
        GoRoute(
          path: 'login',
          builder: (context, state) => const LoginPage(),
        ),
        GoRoute(
            path: 'house_list',
            builder: (context, state) {
              var _token = TokenManager().getToken() ?? '';
              if (_token.isEmpty) {
                return LoginPage();
              } else {
                return HousePage();
              }
            }),
        GoRoute(
          path: 'profile',
          builder: (context, state) {
            var _token = TokenManager().getToken() ?? '';
            final userInfo = state.extra;
            if (_token.isEmpty) {
              return LoginPage();
            } else {
              return ProfilePage(
                userInfo: userInfo as Map,
              );
            }
          },
        ),
      ],
    ),
  ],
);

class MyNavigatorObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    debugPrint('did push route' + route.toString());
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    debugPrint('did pop route' + route.toString());
  }
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // 使用go_router 实现路由
    return MaterialApp.router(
      routerConfig: _goRouter,
    );

    // 原生路由配置方式
    // return MaterialApp(
    //   routes: {
    //     '/': (context) => const TabBarPage(),
    //     '/detail': (context) => NoticeDetail(),
    //   },
    //   onGenerateRoute: (settings) {
    //     var _token = TokenManager().getToken() ?? '';
    //     if (_token.isEmpty && settings.name != '/login') {
    //       return MaterialPageRoute(builder: (context) => LoginPage());
    //     }
    //     if (settings.name == '/profile') {
    //       return MaterialPageRoute(
    //           builder: (context) => ProfilePage(
    //                 userInfo: settings.arguments as Map,
    //               ));
    //     }
    //     if (settings.name == '/house_list') {
    //       return MaterialPageRoute(builder: (context) => HousePage());
    //     }
    //     return null;
    //   },
    //   initialRoute: '/',
    // );
  }
}

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

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

2. 路由跳转传递参数

传递对象

Dart 复制代码
    context.go(
                      '/profile',
                      extra: userInfo,
                    );
                    
    GoRoute(
          path: 'detail/:id',
          builder: (context, state) {
            final id = state.pathParameters['id'];
            return NoticeDetail(
              id: id.toString(),
            );
          },
          // pageBuilder: (context, state) {
          //   return CustomTransitionPage(
          //     key: state.pageKey,
          //     transitionsBuilder: (context, animation, secondaryAnimation, child) {
          //       // Change the opacity of the screen using a Curve based on the the animation's value
          //       return FadeTransition(
          //         opacity:
          //         CurveTween(curve: Curves.easeInOutCirc).animate(animation),
          //         child: child,
          //       );
          //     },
          //     child: Container(),
          //   );
          // },
        ),

路径传参

Dart 复制代码
context.go('/detail/${item['id']}');

GoRoute(
          path: 'profile',
          builder: (context, state) {
            var _token = TokenManager().getToken() ?? '';
            final userInfo = state.extra;
            if (_token.isEmpty) {
              return LoginPage();
            } else {
              return ProfilePage(
                userInfo: userInfo as Map,
              );
            }
          },
        ),

3. 跳转拦截

go_router提供全局重定向,比如在没有登录的用户,需要跳转到登录页面.在 GoRouter 中,可以通过redirect 参数配置重定向.

c 复制代码
redirect: (BuildContext context, GoRouterState state) {
    final isLogin = false;// your logic to check if user is authenticated
    if (!isLogin) {
      return '/login';
    } else {
      return null; // return "null" to display the intended route without redirecting
    }
  }

4. 路由跳转监听

Dart 复制代码
class MyNavigatorObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    print('did push route');
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    print('did pop route');
  }
}

拓展知识

使用方式

bash 复制代码
flutter pub add go_router

总结

go_router的特点:

  • 使用模板语法解析路由路径和路由查询(query)参数;
  • 支持单个目标路由展示多个页面(子路由);
  • 重定向:可以基于应用状态跳转到不同的URL,比如用户没有登录时跳转到登录页;
  • 使用 StatefulShellRoute 可以支持嵌套的 Tab 导航;
  • 同时支持 Material 风格和 Cupertino 风格应用;
  • 兼容 Navigator API 。
相关推荐
GoppViper5 分钟前
golang从http请求中读取xml格式的body,并转成json
xml·后端·http·golang
是jin奥9 分钟前
Golang 逃逸分析(Escape Analysis)理解与实践篇
开发语言·后端·golang
火柴就是我1 小时前
flutter移除ExpansionTile的上下划线
flutter
ikgade1 小时前
Leaflet 接入天地图服务
javascript·html·leaflet·天地图
wy3136228211 小时前
android——Groovy gralde 脚本迁移到DSL
android·前端·javascript
技术卷2 小时前
Gin框架操作指南03:HTML渲染
golang·gin
方应杭2 小时前
Cursor 成功让我卸载了 VSCode
javascript
安冬的码畜日常2 小时前
【玩转 JS 函数式编程_014】4.1 JavaScript 纯函数的相关概念(下):纯函数的优势
开发语言·javascript·ecmascript·函数式编程·js·functional·原生js
qq_172805593 小时前
GO Practise
开发语言·后端·golang·go