How do you implement an auth guard for protected routes?
TL;DR: In go_router, use the redirect callback — check auth state and return '/login' if unauthenticated. Use refreshListenable to make the guard reactive to auth state changes.
Full Answer
An auth guard redirects unauthenticated users to the login screen and lets authenticated users through. In go_router, this is a first-class feature via redirect.
refreshListenable accepts a Listenable (like a ChangeNotifier) that tells go_router to re-evaluate redirects when auth state changes — e.g., after login or logout.
After a successful login, use context.go('/') rather than pop — this prevents the user from back-navigating to the login screen.
Code Examples
Navigating to /profile when logged out → redirected to /login. After login, authModel notifies → redirect re-runs → navigates to /
Common Mistakes
- ✗Not adding refreshListenable — redirect doesn't run after login, user stays on login screen
- ✗Redirecting to /login from /login — causes infinite redirect loop
Interview Tip
The refreshListenable detail is what separates developers who understand go_router deeply from those who copy-paste examples.