当前位置: 首页 > news >正文

Flutter GoRouter 路由导航详解

Flutter GoRouter 路由导航详解

一、GoRouter 概述

GoRouter 是 Flutter 官方推荐的路由管理库,提供声明式路由配置和类型安全的导航。

1.1 安装依赖

dependencies: go_router: ^12.0.0

二、基本配置

2.1 创建路由配置

import 'package:go_router/go_router.dart'; final GoRouter router = GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return const HomePage(); }, ), GoRoute( path: '/details/:id', builder: (BuildContext context, GoRouterState state) { return DetailPage(id: state.pathParameters['id']!); }, ), ], );

2.2 配置 MaterialApp

class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( routerConfig: router, title: 'GoRouter Demo', ); } }

三、路由导航

3.1 基本导航

// 导航到指定路径 context.push('/details/123'); // 导航并替换当前页面 context.pushReplacement('/details/123'); // 返回上一页 context.pop(); // 返回到根页面 context.popUntil((route) => route.isFirst);

3.2 带参数导航

// 路径参数 context.push('/user/${user.id}'); // 查询参数 context.push('/search?q=flutter'); // 额外参数 context.push('/details', extra: {'data': myData});

四、路由守卫

4.1 全局守卫

final GoRouter router = GoRouter( routes: [...], redirect: (BuildContext context, GoRouterState state) { final bool isLoggedIn = // 检查登录状态 if (!isLoggedIn && state.location != '/login') { return '/login'; } return null; }, );

4.2 路由级别守卫

GoRoute( path: '/profile', builder: (context, state) => const ProfilePage(), redirect: (context, state) { final bool isLoggedIn = // 检查登录状态 return isLoggedIn ? null : '/login'; }, );

五、嵌套路由

5.1 配置嵌套路由

GoRoute( path: '/dashboard', builder: (context, state) => const DashboardPage(), routes: [ GoRoute( path: 'settings', builder: (context, state) => const SettingsPage(), ), GoRoute( path: 'profile', builder: (context, state) => const ProfilePage(), ), ], );

5.2 使用 ShellRoute

final GoRouter router = GoRouter( routes: [ ShellRoute( builder: (context, state, child) { return Scaffold( body: child, bottomNavigationBar: BottomNavigationBar( items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'), BottomNavigationBarItem(icon: Icon(Icons.settings), label: 'Settings'), ], ), ); }, routes: [ GoRoute( path: '/', builder: (context, state) => const HomePage(), ), GoRoute( path: '/settings', builder: (context, state) => const SettingsPage(), ), ], ), ], );

六、类型安全路由

6.1 使用 TypedGoRoute

@TypedGoRoute<HomeRoute>(path: '/') class HomeRoute extends GoRouteData { const HomeRoute(); @override Widget build(BuildContext context, GoRouterState state) { return const HomePage(); } } @TypedGoRoute<DetailRoute>(path: '/details/:id') class DetailRoute extends GoRouteData { const DetailRoute({required this.id}); final String id; @override Widget build(BuildContext context, GoRouterState state) { return DetailPage(id: id); } }

6.2 类型安全导航

// 使用类型安全导航 HomeRoute().go(context); DetailRoute(id: '123').push(context);

七、实战案例

7.1 完整路由配置

final GoRouter router = GoRouter( initialLocation: '/', routes: [ GoRoute( path: '/', name: 'home', builder: (context, state) => const HomePage(), ), GoRoute( path: '/login', name: 'login', builder: (context, state) => const LoginPage(), ), GoRoute( path: '/dashboard', name: 'dashboard', builder: (context, state) => const DashboardPage(), redirect: (context, state) { final authState = Provider.of<AuthState>(context, listen: false); return authState.isLoggedIn ? null : '/login'; }, routes: [ GoRoute( path: 'profile', name: 'profile', builder: (context, state) => const ProfilePage(), ), GoRoute( path: 'settings', name: 'settings', builder: (context, state) => const SettingsPage(), ), ], ), ], errorBuilder: (context, state) => const ErrorPage(), );

7.2 使用路由信息

class DetailPage extends StatelessWidget { const DetailPage({super.key}); @override Widget build(BuildContext context) { final GoRouterState state = GoRouterState.of(context); final String id = state.pathParameters['id']!; final String? query = state.uri.queryParameters['q']; return Scaffold( appBar: AppBar(title: const Text('详情')), body: Center( child: Column( children: [ Text('ID: $id'), if (query != null) Text('查询: $query'), ], ), ), ); } }

八、总结

GoRouter 提供了强大的路由管理功能:

  1. 声明式配置- 集中配置所有路由
  2. 类型安全- TypedGoRoute 确保类型安全
  3. 路由守卫- 全局和路由级别守卫
  4. 嵌套路由- 支持复杂的页面结构
  5. ShellRoute- 共享布局的路由

合理使用可以构建清晰的导航结构。

http://www.gsyq.cn/news/1424277.html

相关文章:

  • 网盘直链解析终极指南:一键解锁高速下载体验
  • 如何快速解锁QQ音乐加密文件:qmcdump音频解密工具终极指南
  • 2026年横评10款降AI率工具:一键锁定高效助手! - 降AI小能手
  • 179、运动控制中的行业标准:机器人安全标准ISO 10218
  • 告别PuTTY!Win10/Server 2019自带的OpenSSH客户端,这样用才顺手
  • 【Agent智能体10 | 反思设计模式-AI数据分析的可视化实战】
  • 别再死磕Vivado了!用VSCode写ZYNQ代码,效率翻倍的保姆级配置指南
  • 多 Agent 对证循环协作架构:Hermes + Claude Code + Codex 三角色工作流实战
  • WarcraftHelper魔兽争霸III优化工具:5分钟解锁游戏全部潜力,告别老旧限制
  • Arm CCI-550/CCI-500地址通道带宽异常分析与优化
  • 这6个动作让python selenium爬虫规避检测
  • 【Claude NPV分析权威指南】:20年财务AI专家首曝大模型估值新范式,3步精准测算项目真实价值
  • Linux服务器内存升级避坑指南:手把手教你用dmidecode查清空余卡槽和兼容参数
  • 180、运动控制中的行业标准:CNC标准ISO 841
  • 哪些25-30万五座SUV车型值得选?2026年5月推荐TOP5评测家用空间案例适用场景 - 品牌推荐
  • dto 转entity方法
  • 抖音下载神器终极指南:一键获取无水印视频的完整教程
  • 银河麒麟V10系统下,用vsftpd搭建FTP服务器的保姆级避坑指南
  • 2025-2026年北京定制游旅行社推荐:口碑好的服务企业团建方案落地难案例 - 品牌推荐
  • 2026年杭州权威赋能教育学校评测:浙江青少年叛逆学校、浙江青少年夜不归宿、浙江青少年心理咨询学校、浙江青少年心理辅导学校选择指南 - 优质品牌商家
  • 如何告别多显示器鼠标跳跃?LittleBigMouse的智能DPI感知技术揭秘
  • 离线环境救星:手把手教你用DISM命令搞定Win10 .NET 3.5安装(告别0x8024402c错误)
  • 国内合规垫圈生产企业实测排行:防松垫圈、垫圈定制、DTI垫圈、压力指示垫圈、双叠自锁垫圈、接地垫圈、垫圈选择指南 - 优质品牌商家
  • Win11 WSL2 + Ubuntu 18.04:手把手教你配置ROS开发环境并跑通第一个rviz
  • 2026年5月留香沐浴露品牌推荐:十大排名运动后留香评测专业价格 - 品牌推荐
  • Sysinternals Autoruns实战:从“计划任务”里挖出潜伏的挖矿脚本(附排查思路)
  • 基于大语言模型的生成式智能体架构设计与应用实践
  • 2026年5月留香沐浴露品牌推荐:十大专业评测持久留香价格适用场景 - 品牌推荐
  • Hugging Face数据集实战指南:10大精选与NLP模型微调全流程
  • 2026年节日送礼毛绒玩具怎么选:五家优选品牌深度解析 - 科技焦点