Sub topic 12
Redirects and guards around the shell
This chapter assumes you have built a StatefulShellRoute.indexedStack with StatefulShellBranch tabs, and that you know GoRouter, GoRoute and context.go. Here you will add sign-in guards to that app. You will also see how redirects interact with tabs, branch stacks and deep links.
What a redirect is
A redirect is a function that go_router calls before it shows a location. It receives the BuildContext and a GoRouterState. It returns one of two things:
null, which means "no change, continue to this location".- A location string, which means "go there instead".
go_router then runs the redirect again on the new location. It repeats until a redirect returns null or it reaches redirectLimit, which defaults to 5. A redirect can also return a Future, so an async check such as reading a token from storage is allowed.
The shell does not change this model. A StatefulShellRoute is only part of the route tree, so every location inside a tab goes through the same redirect pipeline as any other location.
Where redirects can live
| Level | Declared on | Runs when |
|---|---|---|
| Top-level | `GoRouter(redirect: ...)` | On every navigation, first |
| Route-level | `GoRoute(redirect: ...)` | When the location matches that route or one of its sub-routes |
| Shell-level | `StatefulShellRoute.indexedStack(redirect: ...)` | When the location matches any route under the shell |
StatefulShellBranch has no redirect parameter. To guard a single tab, put the redirect on the branch's top-level GoRoute.
The top-level redirect runs first. Route-level and shell-level redirects run afterwards, for the routes that match the target location. If any of them returns a new location, go_router starts the whole process again with that location.
A sign-in guard for the whole app
The most common guard sends signed-out users to a login screen. The login route sits at the root of the route tree, outside the shell. That means the tab bar is not drawn on the login screen.
The state object is a ChangeNotifier. Passing it to refreshListenable makes go_router re-run the redirect whenever it calls notifyListeners().
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AuthState extends ChangeNotifier {
bool _signedIn = false;
bool get signedIn => _signedIn;
void signIn() {
_signedIn = true;
notifyListeners();
}
void signOut() {
_signedIn = false;
notifyListeners();
}
}
final AuthState authState = AuthState();
final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>();
final GoRouter router = GoRouter(
navigatorKey: rootNavigatorKey,
initialLocation: '/home',
refreshListenable: authState,
redirect: (context, state) {
final atLogin = state.matchedLocation == '/login';
if (!authState.signedIn) {
if (atLogin) return null;
final from = Uri.encodeQueryComponent(state.uri.toString());
return '/login?from=$from';
}
if (atLogin) {
return state.uri.queryParameters['from'] ?? '/home';
}
return null;
},
routes: [
GoRoute(
path: '/login',
builder: (context, state) => const LoginScreen(),
),
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) {
return ScaffoldWithNavBar(navigationShell: navigationShell);
},
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsScreen(),
),
],
),
],
),
],
);
class LoginScreen extends StatelessWidget {
const LoginScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FilledButton(
onPressed: authState.signIn,
child: const Text('Sign in'),
),
),
);
}
}HomeScreen, SettingsScreen and ScaffoldWithNavBar are the widgets from the earlier chapters. The login button never calls context.go. Calling signIn() notifies the router, the redirect runs again, and the user lands on the saved from location.
How the guard behaves
Take a user who opens the deep link /settings while signed out:
- The top-level redirect sees
signedIn == falseand returns/login?from=%2Fsettings. - The redirect runs again on that location.
atLoginis true, so it returnsnulland the login page is shown. - After
signIn(),refreshListenabletriggers the redirect for the current location, which is the login page.atLoginis true and the user is signed in, so it returns/settings. - go_router matches
/settings, selects the Settings branch, and shows the tab bar.
Redirecting to a location inside a branch selects that branch. You never choose a tab index yourself.
Why `matchedLocation`
state.matchedLocation is the location without query parameters. state.uri includes them. Compare against matchedLocation so that /login?from=... still counts as the login page. Use state.uri when you need to preserve the full original request.
Guarding one route or one tab
Use a route-level redirect when only part of the app needs a check. This example protects a billing page under the Settings tab. The canViewBilling flag stands for whatever permission check your app has.
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsScreen(),
routes: [
GoRoute(
path: 'billing',
redirect: (context, state) {
return authState.canViewBilling ? null : '/settings';
},
builder: (context, state) => const BillingScreen(),
),
],
),A redirect on a parent GoRoute also covers its children. If you put a redirect on /settings, it runs for /settings/billing too. This is a convenient way to protect a whole tab, but it means you must not redirect to a location under that same route unless you return null for it. Otherwise you create a loop.
A redirect on the StatefulShellRoute itself covers every tab. That is rarely needed, because the top-level redirect can do the same job with more context about the target.
Redirects and tab switching
goBranch is a navigation request. It asks go_router to go to the branch's last location, or to its initial location if you pass initialLocation: true. That request goes through the redirect pipeline like any other. If a guard rejects it, the user stays on the current tab and ends up wherever the redirect points.
Redirects that run because of refreshListenable apply to the current location. Signing out while on /settings therefore moves the user to the login page immediately, without any tab tap.
Branch stacks outlive the session
Branch navigators keep their stacks while the user is signed out. The redirect hides the shell, but it does not discard the pages inside each branch. After a second user signs in, the old user's stack can reappear, for example a details page for a record the new user should not see.
Choose one of these remedies:
- Call
goBranch(index, initialLocation: true)for each branch before signing out, so every stack returns to its initial location. - Build a new
GoRouterafter sign-out, so all navigator state is discarded. - Make the pages themselves safe. Load their data from a source that depends on the current user, and let it fail cleanly for a different user.
The third option is the most robust, because it does not rely on the navigation layer for data privacy.
Pitfalls
- Redirect loops. A rule such as "if not signed in, go to
/login" without anatLogincheck redirects forever. go_router stops atredirectLimitand shows its error page. Always returnnullwhen the user is already at the destination. - Missing
refreshListenable. Without it, the redirect runs only on navigation. A user who signs out stays on a protected page until they tap something. - Navigating inside a redirect. Do not call
context.goinside a redirect. Return the new location instead. - Unsaved destination. If you return a plain
/login, the user loses the page they asked for. Pass it along, asfromdoes above. - Full-screen routes. A route with
parentNavigatorKey: rootNavigatorKeyis still part of the route tree, so the same redirects apply to it. - Slow async checks. An async redirect delays every navigation. Keep the check fast, or read a cached value held in your
ChangeNotifier.
Exercise
A signed-out user opens the deep link /settings/billing, and your top-level redirect is the one shown in this chapter. What location does the redirect return first, and where does the user land after signing in?
Show answer
The first redirect returns /login?from=%2Fsettings%2Fbilling, because the user is signed out and not at the login page. After signIn() notifies refreshListenable, the redirect runs on the login location, sees a signed-in user at /login, and returns the decoded from value, /settings/billing. go_router then selects the Settings branch and shows the billing page inside the shell. If a route-level redirect on billing rejects the user, that redirect runs next and may send them elsewhere.
Exercise
Your redirect contains only if (!authState.signedIn) return '/login';. Why does the app fail with a redirect error, and what is the smallest fix?
Show answer
The login route is itself a location. While the user is signed out, the redirect runs on /login, returns /login again, and repeats until redirectLimit is reached. The fix is to return null when state.matchedLocation == '/login', so the redirect stops once the user is at the login page.