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
相关产品推荐
相关产品推荐

