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

Flutter中使用go_router+go_router_builder如何获取当前上下文?

在Flutter中使用go_router与go_router_builder时,redirect方法无法获取Home页面的Bloc上下文问题

我在Flutter项目中使用go_router搭配go_router_builder开发路由,遇到一个问题:redirect方法仅提供应用级上下文,我需要在路由到protected页面时,访问Home页面外层包裹的BlocProviders,但不想通过额外参数传入BuildContext来避免代码杂乱。尝试过用全局导航键获取Home页面的当前上下文,但该方法无效。

应用结构

- splash <- Stateless Widget
-- home <- Stateless Widget
--- protected <- Stateless Widget
-- sign in <- Stateless Widget

相关代码

@TypedGoRoute<SplashRoute>(
  path: '/',
  name: 'Splash',
)
class SplashRoute extends GoRouteData {
  ...
}

@TypedGoRoute<SignInRoute>(
  path: '/sign-in',
  name: 'Sign In',
)
class SignInRoute extends GoRouteData {
  ...
}

@TypedShellRoute<HomeRoute>(
  routes: <TypedGoRoute<GoRouteData>>[
    TypedGoRoute<ProtectedRoute>(
      path: '/home/protected',
      name: 'Protected',
    ),
  ],
)
class HomeRoute extends ShellRouteData {
  ...
}

class ProtectedRoute extends GoRouteData {
  @override
  FutureOr<String?> redirect(BuildContext context, GoRouterState state) {
    // 此处context无法获取MyCubit,因为它被包裹在HomePage widget外层
    if(context.read<MyCubit>().state is! MyStateSuccess){
      ...
    }

    return super.redirect(context, state);
  }

  ...
}

内容的提问来源于stack exchange,提问作者anonymous-dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 10:57:36