I am developing an app in Flutter using go_router
package. The auth logic is as follows:
You can see the detailed situation in this link:
Inside the redirect
callback, you can check the current auth state and the current path, and return the home route when the auth state is 'authenticated' and the current path is 'login'.
For example:
redirect: (_, state) {
final authState = ... // Get auth state based on your auth/state management strategy
final currentPath = state.fullPath; // There are other options, such as `state.matchedLocation` and `state.name`
if (authState == AuthState.authenticated && currentPath == '/login') {
return '/home';
}
}
Additionally, you have to make sure that you navigate to the login screen with the context.go
method, as context.push
won't change the current location, which causes the state
would still be in the previous route (in this case, the home route).
Change
context.push('/login')
to
context.go('/login')
The package has an official example that implements this behavior:
I also made an example with a slightly different approach to simplify the logic: