flutterdartroutesnavigation

Navigating Users Between Pages Without Allowing Back Navigation


GoRouter: How to navigate to the home page after login and prevent back navigation to the login page in Flutter (Web and Mobile)

I am building an e-commerce app for both web and mobile using Flutter, and I'm using the GoRouter package for routing. When the user logs in, I want to navigate them to the home page (/home) and prevent them from navigating back to the login page (using the back button or browser back action on the web).

Here is what I've tried so far:

After verifying the login credentials, I used context.replace('/home'); in the onTap method of my sign-in button to navigate to the home page. However, the issue is that users can still navigate back to the login page using the browser's back button or the device's back button. What I'm looking for:

A solution that ensures users cannot navigate back to the login page once they are successfully logged in.


Solution

  • If you create splash screen as well then add below code inside that and use pushReplacement, I have used same scenario in my project hope its help to you.

     @override
      Future<void> initState() async {
        super.initState();
        SharedPreferences prefs = await SharedPreferences.getInstance();
        var email = prefs.getString('email');
        prefs.setString('email', 'useremail@gmail.com');
          if (email != null) {
            GoRouter.of(context).pushReplacement(/homeRoute);
          } else {
            GoRouter.of(context).pushReplacement(loginRoute);
          }
    
      }
    

    Below is your router.dart file

    class AppRouter {
      static final GoRouter router = GoRouter(
        routes: [
        GoRoute(
            path: '/homeRoute',
            builder: (context, state) => const HomeScreen(),
          ),
        GoRoute(
            path: '/loginRoute',
            builder: (context, state) => const LoginScreen(),
          ),
         ]
       }
    

    Refer this how to save isLogin in SharedPreferences