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

Go Router调用context.push时始终重定向至/register页面问题

问题根源

你的重定向逻辑存在漏洞:在未认证状态(AuthUnauthenticatedState)下,只允许访问/register,其他所有路径都会被强制重定向到/register。当你从/register跳转/login时,GoRouter先尝试导航到/login,随后触发重定向检查——因为当前是未认证状态,且/login不在允许列表里,所以被拉回/register。

修复方案

修改redirect方法的判断逻辑,把/login也加入未认证状态下允许访问的路径白名单:

redirect: (context, state) {
  print(state.location);
  final isUnauthenticated = authBloc.state is AuthUnauthenticatedState;
  final allowedUnauthedPaths = {'/register', '/login'};
  
  if (isUnauthenticated) {
    // 如果当前路径不在允许的未认证路径列表里,重定向到/register
    if (!allowedUnauthedPaths.contains(state.location)) {
      return '/register';
    }
  } else if (authBloc.state is AuthAuthenticatedState) {
    // 已认证状态下,直接跳转到/app
    return '/app';
  }
  // 返回null表示不触发重定向
  return null;
}
额外优化点
  • 你的GoRouterRefreshStream在初始化时立刻调用了notifyListeners(),这会导致GoRouter在启动时额外触发一次重定向。如果不需要这个初始触发,可以移除这行代码:
GoRouterRefreshStream(Stream<dynamic> stream) {
  // 移除这行:notifyListeners();
  _subscription = stream.asBroadcastStream().listen(
        (dynamic _) => notifyListeners(),
      );
}
  • 用变量提取重复的状态判断,让代码更易读,比如示例中的isUnauthenticated。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:05:07