Sub topic 12
Redirects and guards around the shell
This chapter assumes that you know Dart, Flutter widgets, Navigator, declarative routing, and basic go_router. You should also understand the earlier StatefulShellRoute.indexedStack setup with a home branch and a settings branch.
A redirect is a function that changes the requested location before the page is shown. A guard is the rule that decides whether the redirect is needed. Common guards check authentication, account roles, or whether required data has been loaded.
Where redirects run
A GoRouter can have a top-level redirect. This is useful for rules that apply to every route, including routes inside a shell. A GoRoute can also have its own redirect. This is useful for rules that apply only to one page or branch.
| Redirect location | Best use | Example |
|---|---|---|
| `GoRouter.redirect` | Application-wide access rules | Send signed-out users to login |
| Shell route redirect | Rules for the shell | Require an account before showing tabs |
| Nested `GoRoute.redirect` | Page-specific rules | Restrict an admin page |
The top-level redirect runs before a route-specific redirect. Return a location string to redirect, or return null to allow navigation. The router reevaluates redirects when a listenable object passed to refreshListenable changes.
Guarding the shell and its pages
The following example keeps the login page outside the shell. Signed-out users cannot see the tab bar. The nested admin route has an additional role check.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AuthState extends ChangeNotifier {
bool isSignedIn = false;
bool isAdmin = false;
void signIn() {
isSignedIn = true;
notifyListeners();
}
void signOut() {
isSignedIn = false;
isAdmin = false;
notifyListeners();
}
}
final auth = AuthState();
final router = GoRouter(
initialLocation: '/home',
refreshListenable: auth,
redirect: (context, state) {
final onLogin = state.matchedLocation == '/login';
if (!auth.isSignedIn && !onLogin) {
final from = Uri.encodeComponent(state.uri.toString());
return '/login?from=$from';
}
if (auth.isSignedIn && onLogin) {
return state.uri.queryParameters['from'] ?? '/home';
}
return null;
},
routes: [
GoRoute(
path: '/login',
builder: (context, state) => const LoginPage(),
),
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) {
return AppShell(navigationShell: navigationShell);
},
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomePage(),
routes: [
GoRoute(
path: 'admin',
redirect: (context, state) {
return auth.isAdmin ? null : '/home';
},
builder: (context, state) => const AdminPage(),
),
],
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsPage(),
),
],
),
],
),
],
);
class LoginPage extends StatelessWidget {
const LoginPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => auth.signIn(),
child: const Text('Sign in'),
),
),
);
}
}
class AppShell extends StatelessWidget {
const AppShell({super.key, required this.navigationShell});
final StatefulNavigationShell navigationShell;
@override
Widget build(BuildContext context) {
return Scaffold(
body: navigationShell,
bottomNavigationBar: NavigationBar(
selectedIndex: navigationShell.currentIndex,
onDestinationSelected: navigationShell.goBranch,
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(
icon: Icon(Icons.settings),
label: 'Settings',
),
],
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) =>
const Center(child: Text('Home'));
}
class AdminPage extends StatelessWidget {
const AdminPage({super.key});
@override
Widget build(BuildContext context) =>
const Center(child: Text('Admin'));
}
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@override
Widget build(BuildContext context) =>
const Center(child: Text('Settings'));
}The from query parameter preserves the requested location. After signing in, the user can return to that location instead of always landing on /home. The admin redirect is relative to the home branch's route tree, but its destination is an absolute location.
Common mistakes
- Do not call
context.gofrom inside a redirect. Return the destination instead. - Do not read authentication state only once when constructing the router. Use
refreshListenableor rebuild the router when the state changes. - Keep login and other public pages outside the shell when signed-out users should not see the shell UI.
- Use unique absolute paths for branch roots. Nested child paths are relative to their parent.
- Test deep links such as
/home/admin, not only tab taps. Guards must work when the application starts at a protected location.
Exercise
A signed-out user opens /home/admin. Which guard runs first, and where should the user go after signing in?
Show answer
The top-level authentication redirect runs first and sends the user to /login while preserving the original location. After signing in, the router can return to /home/admin, where the admin-role redirect runs.