Home > Enterprise >  How to forbid navigating back to Login page after successful login?
How to forbid navigating back to Login page after successful login?

Time:11-14

I have a question. How to achieve this behavior using auto_route's AutoRedirectGuard:

  1. User opens Flutter app in browser but session expired and is redirected to the Login Page.
  2. User successfully logs in.
  3. User is redirected to Home page.
  4. 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(),
...
);
  • Related