Flutter中GoRouter的push/go/pushNamed导航失效求助
Flutter GoRouter导航无效问题排查与修复
核心问题原因
你在main函数中每次调用MyAppRouter()都会创建一个全新的GoRouter实例,而页面中执行context.goNamed时使用的是另一个实例的上下文,导致路由状态无法共享,跳转操作无法触发页面更新。
修复方案
确保全局只有一个GoRouter实例,推荐使用单例模式改造路由配置类:
1. 改造MyAppRouter为单例
class MyAppRouter{ // 单例实例,全局唯一 static final MyAppRouter _instance = MyAppRouter._internal(); factory MyAppRouter() => _instance; MyAppRouter._internal(); final GoRouter router = GoRouter( routes: [ GoRoute( name: MyAppRouteConstants.defaultRouteName, path: '/', pageBuilder: (context, state){ return MaterialPage(child: UnknownPage()); } ), GoRoute( name: MyAppRouteConstants.registerRouteName, path: '/register', pageBuilder: (context, state){ return MaterialPage(child: RegisterPage()); } ), GoRoute( name: MyAppRouteConstants.loginRouteName, path: '/login', pageBuilder: (context, state){ return MaterialPage(child: LogInPage()); } ), GoRoute( name: MyAppRouteConstants.profileRouteName, path: '/profile_page', pageBuilder: (context, state){ return MaterialPage(child: HomePage()); } ), GoRoute( name: MyAppRouteConstants.addRecipeRouteName, path: '/add_recipe', pageBuilder: (context, state){ return MaterialPage(child: CreateActivityPage()); } ), GoRoute( name: MyAppRouteConstants.publicRecipeRouteName, path: '/public_recipes', pageBuilder: (context, state){ return MaterialPage(child: PublicRecipePage()); } ), GoRoute( name: MyAppRouteConstants.favoritesRouteName, path: '/favorites', pageBuilder: (context, state){ return MaterialPage(child: FavoritesPage()); } ), ], errorPageBuilder: (context, state){ return MaterialPage(child: UnknownPage()); } ); }
2. 保持main中的路由实例一致
runApp( OverlaySupport( child: MaterialApp.router( debugShowCheckedModeBanner: false, theme: new ThemeData(scaffoldBackgroundColor: White_Anti_Flash), routeInformationParser: MyAppRouter().router.routeInformationParser, routerDelegate: MyAppRouter().router.routerDelegate, routeInformationProvider: MyAppRouter().router.routeInformationProvider, ), ), );
额外排查点
- 确认页面使用的
context未被自定义Navigator包裹:如果页面内部嵌套了Navigator,会导致context指向内部导航器,而非GoRouter的全局实例。 - 检查是否存在
redirect逻辑:如果GoRouter配置了redirect,可能会拦截跳转请求,需要确保跳转路径符合redirect规则。 - 验证路由名称与路径匹配:确认
MyAppRouteConstants.profileRouteName对应的name和path没有拼写错误。
内容的提问来源于stack exchange,提问作者TheFallen1
相关产品推荐
相关产品推荐

