使用auto_route时Flutter路由导航报错,需实现登录校验跳转
Flutter AutoRoute 路由循环报错及授权跳转解决方案
启动应用时使用AutoRoute做授权校验出现循环导航报错,需求为:启动时检查用户授权状态,已授权直接进入MainRoute,未授权进入AuthRoute。
错误原因
当前路由配置将AuthRoute设为初始路由并绑定AuthGuard,导致逻辑冲突:
- 已登录时,
resolver.next()会继续加载AuthRoute,不符合跳转到MainRoute的需求 - 未登录时,guard重复push
AuthRoute,造成路由栈循环入栈报错
解决方案
1. 调整路由配置
修改AppRouter,新增无界面的初始引导路由触发校验,避免在目标页面上绑定guard引发循环:
class AppRouter extends _$AppRouter { @override List<AutoRoute> get routes => [ // 初始引导路由,仅用于触发AuthGuard AutoRoute( path: '/', initial: true, guards: [AuthGuard()], page: RedirectRoute.page, redirectTo: '/auth', // 默认指向登录页,实际由guard决定最终跳转 ), AutoRoute(page: AuthRoute.page, path: '/auth'), AutoRoute( page: MainRoute.page, path: '/main', children: [ AutoRoute(path: 'dashboard', page: DashboardRoute.page), AutoRoute(path: 'crypto-list', page: CryptoListRoute.page), AutoRoute(path: 'settings', page: SettingsRoute.page), ], ), AutoRoute(page: CoinDetailsRoute.page, path: '/coin-details'), ]; }
2. 修复AuthGuard逻辑
更新guard逻辑,直接根据登录状态跳转目标页面,阻止原导航避免循环:
class AuthGuard extends AutoRouteGuard { @override void onNavigation(NavigationResolver resolver, StackRouter router) async { // 使用全局实例获取登录状态(避免每次创建新AuthProvider导致状态丢失) final AuthProvider appState = GetIt.I<AuthProvider>(); if (appState.isLoggedIn) { // 已登录,替换路由到MainRoute await router.replace(const MainRoute()); resolver.next(false); // 阻止原导航流程 } else { // 未登录,替换路由到AuthRoute await router.replace(const AuthRoute()); resolver.next(false); } } }
3. 登录按钮跳转优化
登录成功后使用replace替换当前路由,避免返回栈中保留登录页:
void onPressedMethod(bool isRegister) { // 先更新全局登录状态 GetIt.I<AuthProvider>().updateLoginStatus(true); // 替换路由到MainRoute AutoRouter.of(context).replace(const MainRoute()); }
关键注意事项
- 不要在初始路由的目标页面上绑定相同guard,防止循环触发校验
- 必须使用全局状态管理实例(如GetIt、Provider)获取登录状态,避免每次创建新对象导致状态读取错误
- 登录状态变更后,使用
replace而非push跳转路由,保证返回栈的合理性
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

