Sub topic 9
Redirects and authentication guards
This chapter assumes Dart null safety, Flutter widgets, Navigator, and ChangeNotifier. It also assumes you have added go_router to your Flutter project.
A redirect is a function that changes the requested location before its page is shown. An authentication guard uses this function to keep signed-out users away from protected routes. The redirect returns a location such as '/login', or returns null to allow navigation.
How a redirect works
A router evaluates its redirect when the app starts and whenever navigation changes the current location. The GoRouterState argument describes that location.
A common guard has three cases:
- A signed-out user going anywhere except
/loginis sent to/login. - A signed-in user visiting
/loginis sent to/. - All other navigation is allowed by returning
null.
Connect authentication state to GoRouter
ChangeNotifier is useful when authentication can change while the app is running. Calling notifyListeners tells the router to evaluate its redirect again.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AuthState extends ChangeNotifier {
bool _loggedIn = false;
bool get loggedIn => _loggedIn;
void logIn() {
_loggedIn = true;
notifyListeners();
}
void logOut() {
_loggedIn = false;
notifyListeners();
}
}
final auth = AuthState();
final router = GoRouter(
initialLocation: '/',
refreshListenable: auth,
redirect: (context, state) {
final atLogin = state.matchedLocation == '/login';
if (!auth.loggedIn) {
return atLogin ? null : '/login';
}
if (atLogin) {
return '/';
}
return null;
},
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/login',
builder: (context, state) => const LoginScreen(),
),
],
);
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => auth.logOut(),
child: const Text('Sign out'),
),
),
);
}
}
class LoginScreen extends StatelessWidget {
const LoginScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sign in')),
body: Center(
child: ElevatedButton(
onPressed: () => auth.logIn(),
child: const Text('Sign in'),
),
),
);
}
}
void main() {
runApp(MaterialApp.router(routerConfig: router));
}refreshListenable: auth is important. Without it, calling logIn changes the state but does not automatically cause the router to reconsider /login.
Avoid redirect loops
A redirect must eventually return null or reach a location whose redirect result is different. The atLogin check prevents this loop:
/redirects to/login./loginredirects to/loginagain.- The router keeps repeating the redirect.
Keep authentication checks in one router-level redirect when possible. For role-based access, inspect the requested location and return a suitable page, such as /forbidden. Do not put secrets in query parameters. URLs can appear in browser history, logs, and analytics.
Exercise
Why does the example return null when a signed-out user is already at /login?
Show answer
Returning null allows the login route to display and prevents a redirect loop.