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

如何在go_router的redirect中取消路由跳转?

在GoRouter中阻止非付费用户跳转的实现方式

在GoRouter的redirect回调里没有直接返回false取消路由的写法,要实现阻止跳转的效果,你可以返回用户当前所在的路由路径,让GoRouter导航回当前页面(实际不会发生页面跳转),以此拦截目标路由的跳转请求。

基础实现代码

redirect: (BuildContext context, GoRouterState state) {
  final authState = AuthState.of(context);
  // 判断用户是非付费用户,且当前请求的路由不是当前页面(避免无限重定向)
  if (authState.isNotPremiumUser && state.subloc != state.fullPath) {
    // 返回当前路由路径,拦截目标跳转
    return state.subloc;
  }
  // 允许跳转时返回null
  return null;
},

针对特定付费路由的拦截

如果只需要拦截指定的几个付费路由,可以先定义需要拦截的路由列表,再做判断:

// 提前定义需要拦截的付费路由
final premiumOnlyRoutes = ['/premium-content', '/vip-dashboard'];

redirect: (BuildContext context, GoRouterState state) {
  final authState = AuthState.of(context);
  // 判断用户是非付费用户,且目标路由属于付费路由
  if (authState.isNotPremiumUser && premiumOnlyRoutes.contains(state.fullPath)) {
    // 返回当前页面路径,阻止跳转
    return state.subloc;
  }
  return null;
},

注意:添加state.subloc != state.fullPath的判断是为了避免当用户已经在当前页面时触发无限重定向的问题,根据你的实际场景可以调整或移除这个判断。

内容的提问来源于stack exchange,提问作者This is the R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:32:36