I have a question. How to achieve this behavior using auto_route's AutoRedirectGuard:
- User opens Flutter app in browser but session expired and is redirected to the Login Page.
- User successfully logs in.
- User is redirected to Home page.
- User cannot click the "back" button and see Login page again.
1, 2, 3 is working. I just can't get the 4th step right. This is the code of the AuthGuard:
class AuthGuard extends AutoRedirectGuard {
final AuthService authService;
bool isLoggedIn;
AuthGuard(this.authService, this.isLoggedIn) {
authService.authChanges.listen((isLoggedIn) {
if (this.isLoggedIn != isLoggedIn) {
this.isLoggedIn = isLoggedIn;
reevaluate(strategy: const ReevaluationStrategy.rePushFirstGuardedRouteAndUp());
}
});
}
@override
Future<void> onNavigation(NavigationResolver resolver, StackRouter router) async {
if (await authService.isLoggedIn()) {
resolver.next();
} else {
redirect(const LoginRoute(), resolver: resolver);
}
}
}
CodePudding user response:
If the user is logged-in and navigating to login redirect them to home page. In onNavigation function.
CodePudding user response:
This is covered in a similar post that you can read the OP here.
You can set up a gate in main.dart conditioned on authentication, and use Navigator.pushReplacement when leaving the AuthScreen.
MaterialApp(
...
home: isLoggedIn ? HomeScreen() : AuthScreen(),
...
);
