You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GoRouter实现路由重定向遇异常:未登录跳转后返回首页

GoRouter路由安全重定向异常问题及解决

问题描述

应用需实现路由安全,使用GoRouter时出现异常:未登录用户访问profile、order、favorites这三个安全路由时,页面先跳转至登录页,随即又自动返回首页,不符合预期。

问题代码

class AppRouter {
  final SessionCubit sessionCubit;

  GoRouter get router => _goRouter;

  AppRouter(this.sessionCubit);

  late final GoRouter _goRouter = GoRouter(
    refreshListenable: GoRouterRefreshStream(sessionCubit.stream),
    initialLocation: APP_PAGE.home.toPath,
    routes: <GoRoute>[
      GoRoute(
        path: APP_PAGE.home.toPath,
        name: APP_PAGE.home.toName,
        builder: (context, state) => MyHomePage(),
      ),
      GoRoute(
        path: APP_PAGE.login.toPath,
        name: APP_PAGE.login.toName,
        builder: (context, state) => const LoginPage(),
      ),
      GoRoute(
        path: APP_PAGE.profile.toPath,
        name: APP_PAGE.profile.toName,
        builder: (context, state) => MyProfile(),
      ),
      GoRoute(
        path: APP_PAGE.page1.toPath,
        name: APP_PAGE.page1.toName,
        builder: (context, state) => const Page1(),
      ),
      GoRoute(
        path: APP_PAGE.error.toPath,
        name: APP_PAGE.error.toName,
        builder: (context, state) => ErrorPage(error: state.extra.toString()),
      ),
      GoRoute(
        path: APP_PAGE.page2.toPath,
        name: APP_PAGE.page2.toName,
        builder: (context, state) => const Page2(),
      ),        
    ],
    debugLogDiagnostics: true,
    errorBuilder: (context, state) => ErrorPage(error: state.error.toString()),
    redirect: (context, state) {
  
      final userAutheticated = sessionCubit.state is Authenticated;
      if (userAutheticated) {
        if (state.subloc == '/login') return '/home';
        if (state.subloc == '/profile') return '/profile';
        if (state.subloc.contains('/page1')) return '/page1';
        return '/home';
      } else {
        if (state.subloc == '/home') {
          return '/home';
        }
        if (state.subloc == '/page2') {
          return '/page2';
        } else {
          return '/login';
        }    
       
      }
    },
  );
}

解决方案(更新于11月5日)

1. 升级GoRouter版本

使用最新版本的go_router 5.1.5,旧版本存在重定向逻辑的固有问题。

2. 修改重定向逻辑

调整重定向判断逻辑,确保只有符合条件时才执行重定向,否则返回null终止重定向流程:

if(!userAutheticated && !onloginPage && !onpublicPage1 && !onPublicPage2 && !onPublicPageN){
        return '/login';
      }
      if (userAutheticated && onloginPage) {
        return '/home';
      }
      // 必须添加此返回,条件不满足时终止重定向
      return null;

额外注意

Flutter Web调试模式下问题仍存在,切换到发布模式后恢复正常。

内容的提问来源于stack exchange,提问作者shroot91

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:40:36