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

如何适配新版GoRouter重写路由重定向逻辑?升级后遇类型错误

适配新版GoRouter的重定向逻辑修改

错误提示的核心是新版GoRouter的redirect回调函数签名变更:现在要求接收两个参数(BuildContext和GoRouterState),且返回类型支持异步的FutureOr<String?>(同步返回String?也兼容)。

只需对原有代码做一处关键调整:给回调函数添加BuildContext参数(即使你用不到这个参数,也必须声明),原有逻辑可以完全保留。

修改后的代码如下:

redirect: (BuildContext context, GoRouterState state) {
  final loggedIn = AuthService.instance.loginInfo.isLoggedIn;
  final isLogging = state.location == '/login';

  if (!loggedIn && !isLogging) return '/login';
  if (loggedIn && isLogging) return '/stores';

  return null;
},

如果后续你的重定向逻辑需要异步操作(比如从本地存储异步读取登录状态),可以直接把函数改成异步的,返回Future<String?>,示例:

redirect: (BuildContext context, GoRouterState state) async {
  final loggedIn = await AuthService.instance.checkLoginStatus();
  final isLogging = state.location == '/login';

  if (!loggedIn && !isLogging) return '/login';
  if (loggedIn && isLogging) return '/stores';

  return null;
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:25:24