Dealing with GoRouter redirection/route-guards. #109
-
Given the following // ...
MaterialApp.router(
// ...
routerConfig: GoRouter(
navigatorKey: rootNavigatorKey,
debugLogDiagnostics: kDebugMode,
initialLocation: DashboardPage.routeName,
routes: routes,
errorPageBuilder: (context, state) => const NoTransitionPage(
child: PageNotFoundPage(),
),
// refreshListenable: ???,
redirect: (BuildContext context, GoRouterState state) {
final isAuthed = use(userCapsule).map((user) => user != null).dataOr(false);
final isOnboardingCompleted = use(onboardingCompletedCapsule).read.dataOr(false) ?? false;
final bool isInAuthFlow = state.uri.toString().contains(AuthenticationPage.routeName);
if (!isOnboardingCompleted && !isAuthed) return OnboardingPage.routeName;
if (isInAuthFlow && isAuthed) return DashboardPage.routeName;
if (isInAuthFlow || isAuthed) return null;
return AuthenticationPage.routeName;
},
),
) How to handle the With Riverpod the same idea applied with |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
I'd normally suggest tossing the router in a capsule but after looking at the GoRouter api it doesn't look like you can update the At the moment I'm not thinking of any better solutions, so since GoRouter doesn't play nicely with ReArch's reactivity here, you will likely need to fallback to the imperative: final container = CapsuleContainerProvider.containerOf(context);
container.read(fooBarCapsule); Within your redirect method. And then make sure the GoRouter won't be accidentally recreated. |
Beta Was this translation helpful? Give feedback.
That seems satisfactory to me. Only two changes I’d suggest:
extension on Container
that has a method called something like “listenableOf” that returns a Listenable + a dispose (which maybe you could automatically handle based on listener count, but that seems out of the scope for what you’re specifically trying to do)And be very sure that the build will not be called ever again. You can toss that listenable init stuff and the GoRouter() call in a use.callonce if you need to.
I think I’d accept a PR for 2. above, if you were willing.