'How to forbid navigating back to Login page after successful login?

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);
    }
  }
}


Solution 1:[1]

If the user is logged-in and navigating to login redirect them to home page. In onNavigation function.

Solution 2:[2]

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(),
...
);

Solution 3:[3]

You can add an after login callback in LoginPage

On your LoginPage, add onLoginCallback parameter

  final void Function(bool)? onLoginCallback;

  const LoginPage({
    Key? key,
    this.onLoginCallback,
  }) : super(key: key);

and then call it whenever user is done logging in

onLoginCallback?.call(true);

In your AuthGuard

 @override
 Future<void> onNavigation(NavigationResolver resolver, StackRouter router) async {
   if (await authService.isLoggedIn()) {
     resolver.next();
   } else {
     router.push(LoginRoute(
       onLoginCallback: (success) {
        if (success) {
          resolver.next();
          router.removeLast(); // <- here is the part so that the user can't go  back to login
        }
       },
     ));
   }
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thuva4
Solution 2 flutteRguy
Solution 3 Tio Irawan