4.3 第三方路由
GoRouter 是目前 Flutter 社区最推荐的路由方案由 Flutter 官方团队维护支持声明式路由、深链、嵌套路由和类型安全参数。一、GoRouter推荐1.1 安装dependencies:go_router:^14.0.01.2 基础配置finalrouterGoRouter(initialLocation:/,debugLogDiagnostics:true,// 开发时打印路由信息routes:[GoRoute(path:/,builder:(context,state)constHomePage(),),GoRoute(path:/login,builder:(context,state)constLoginPage(),),GoRoute(path:/product/:id,builder:(context,state){finalidint.parse(state.pathParameters[id]!);returnProductDetailPage(productId:id);},),GoRoute(path:/search,builder:(context,state){finalquerystate.uri.queryParameters[q]??;returnSearchPage(initialQuery:query);},),],// 路由守卫重定向redirect:(context,state){finalisLoggedInAuthService.isLoggedIn;finalisLoginPagestate.matchedLocation/login;if(!isLoggedIn!isLoginPage)return/login;if(isLoggedInisLoginPage)return/;returnnull;// 不重定向},)voidmain(){runApp(MaterialApp.router(routerConfig:router,),);}1.3 导航操作// 跳转context.go(/product/42);// 替换当前路由context.push(/product/42);// 压栈可返回context.pushReplacement(/home);// 替换栈顶// 带参数context.go(/product/42);// 路径参数context.go(/search?qflutter);// 查询参数// 带 extra 对象非 URL 参数context.push(/product/42,extra:product);// 返回context.pop();context.pop(result_value);// 携带返回值// 判断是否可返回if(context.canPop())context.pop();1.4 ShellRoute嵌套路由 / Tab 导航finalrouterGoRouter(routes:[ShellRoute(builder:(context,state,child)MainShell(child:child),routes:[GoRoute(path:/home,builder:(_,__)constHomePage()),GoRoute(path:/explore,builder:(_,__)constExplorePage()),GoRoute(path:/profile,builder:(_,__)constProfilePage()),],),// 全屏路由不受 Shell 约束GoRoute(path:/login,builder:(_,__)constLoginPage()),],)classMainShellextendsStatelessWidget{finalWidgetchild;constMainShell({super.key,requiredthis.child});overrideWidgetbuild(BuildContextcontext){returnScaffold(body:child,bottomNavigationBar:BottomNavigationBar(currentIndex:_getCurrentIndex(GoRouterState.of(context)),onTap:(index){switch(index){case0:context.go(/home);case1:context.go(/explore);case2:context.go(/profile);}},items:const[BottomNavigationBarItem(icon:Icon(Icons.home),label:首页),BottomNavigationBarItem(icon:Icon(Icons.explore),label:发现),BottomNavigationBarItem(icon:Icon(Icons.person),label:我的),],),);}int_getCurrentIndex(GoRouterStatestate){finallocationstate.matchedLocation;if(location.startsWith(/home))return0;if(location.startsWith(/explore))return1;return2;}}1.5 类型安全路由go_router_builderdev_dependencies:go_router_builder:^2.0.0// 定义类型安全路由partroutes.g.dart;TypedGoRouteHomeRoute(path:/)classHomeRouteextendsGoRouteData{constHomeRoute();overrideWidgetbuild(BuildContextcontext,GoRouterStatestate)constHomePage();}TypedGoRouteProductDetailRoute(path:/product/:id)classProductDetailRouteextendsGoRouteData{finalint id;finalString?tab;constProductDetailRoute({requiredthis.id,this.tab});overrideWidgetbuild(BuildContextcontext,GoRouterStatestate)ProductDetailPage(productId:id,tab:tab??info);}// 使用编译期类型安全constHomeRoute().go(context);ProductDetailRoute(id:42,tab:reviews).push(context);二、AutoRoutedependencies:auto_route:^9.0.0dev_dependencies:auto_route_generator:^9.0.0// 定义路由注解方式RoutePage()classProductDetailPageextendsStatelessWidget{finalint productId;constProductDetailPage({queryParamrequiredthis.productId,super.key});}// 配置路由AutoRouterConfig()classAppRouterextendsRootStackRouter{overrideListAutoRoutegetroutes[AutoRoute(page:HomeRoute.page,initial:true),AutoRoute(page:ProductDetailRoute.page,path:/product/:productId),AutoRoute(page:ProfileRoute.page,guards:[AuthGuard]),];}// 路由守卫classAuthGuardextendsAutoRouteGuard{overridevoidonNavigation(NavigationResolverresolver,StackRouterrouter){if(AuthService.isLoggedIn){resolver.next(true);}else{resolver.redirect(constLoginRoute());}}}三、GetX 路由管理voidmain()runApp(GetMaterialApp(initialRoute:/,getPages:[GetPage(name:/,page:()constHomePage()),GetPage(name:/login,page:()constLoginPage()),GetPage(name:/product/:id,page:()constProductDetailPage(),binding:ProductBinding(),// 自动注入依赖middlewares:[AuthMiddleware()],transition:Transition.rightToLeft,),],));// GetX 导航Get.toNamed(/product/42);Get.offNamed(/home);// 替换当前Get.offAllNamed(/login);// 清空后跳转Get.back();Get.back(result:data);// 获取路径参数finalidGet.parameters[id];// 路由守卫classAuthMiddlewareextendsGetMiddleware{overrideRouteSettings?redirect(String?route){returnAuthService.isLoggedIn?null:constRouteSettings(name:/login);}}// 依赖注入绑定classProductBindingextendsBindings{overridevoiddependencies(){Get.lazyPutProductController(()ProductController());}}小结方案特点推荐场景GoRouter官方维护类型安全深链友好中大型项目首选AutoRoute代码生成类型完整功能丰富大型企业项目GetX 路由与 GetX 生态集成极简已使用 GetX 的项目 下一节4.4 动态与嵌套路由