Auth-protected routes via GoRouter redirect
guarding routes with redirect.
a top-level redirect reads auth state, sends unauthenticated users to login, sends logged-in users away from login, and uses refreshListenable to re-evaluate on auth change.
WHAT THIS TESTS Whether you can express authentication guarding declaratively in the router and avoid the classic pitfalls of redirect loops and stale state.
A GOOD ANSWER COVERS GoRouter accepts a top-level redirect function called before navigation resolves. Inside it you read your auth state, often from a notifier or repository, and inspect the target location via the GoRouterState. The logic returns a path to redirect to, or null to proceed. The core rules: if the user is not authenticated and is not already going to the login or signup route, return the login path; if the user is authenticated but currently on the login route, return the home path; otherwise return null. To make the router re-evaluate when login or logout happens, pass a refreshListenable, typically a Listenable that pulses on auth changes, so the redirect runs again and moves the user appropriately.
COMMON WRONG ANSWERS Forgetting to exempt the login route, which creates an infinite redirect loop. Putting the guard in a widget build method and calling context.go manually, which races with the router. Reading auth state once at startup so logout never redirects. Returning the same location you are on.
LIKELY FOLLOW-UPS Why refreshListenable matters. How do you preserve the originally requested location to return after login. Per-route versus top-level redirect. How do you avoid loops.
ONE CONCRETE EXAMPLE You create GoRouter with a redirect that does: final loggedIn = auth.isLoggedIn; final goingToLogin = state.matchedLocation == '/login'; if not loggedIn and not goingToLogin return '/login'; if loggedIn and goingToLogin return '/home'; return null. You pass refreshListenable: auth, a ChangeNotifier that notifies on sign-in and sign-out. Now visiting /profile while logged out lands on /login, and signing in pulses the listenable so the router re-runs and forwards to /home automatically.
Read the original → docs.page
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.