2
votes

I'm using Navigator.pushReplacementNamed in flutter app to navigate from loginpage to homepage working well, but in my homepage show back arrow button at the appBar and it returns to loginpage when pressing it. What should I do? I tried put leading: Text(''), but when pressing physical back button it still goes back to loginpage.

I have a logout button and I want user to logout only by this button, not from back button

*this is my first question here, sorry for my poor English or any mistakes

3

3 Answers

3
votes

You should use this instead:

.pushNamedAndRemoveUntil(/* Your Route */, (Route<dynamic> route) => false)
1
votes

As I understand your UX flow, the user will always be directed to the login page on the app start. If the user is already logged in, you should avoid navigating to this (at that moment useless) route. Instead try to distinguish in the build method if the user is logged in or not. If the user is already logged in, build the homepage. If the user is not logged in, build the login page. As soon as the user logs in, the state changes and the homepage will be build.

// your stateful component

bool isLoggedIn;

@override
Widget build(BuildContext context) {
  if(isLoggedIn) {
    return _buildHomepage();
  } else {
    return _buildLoginPage();
  }
}

Widget _buildHomepage() {
  // build your homepage
}

Widget _buildLoginPage() {
  // build your login page
}
1
votes

I had this problem today and came across your Post. While PushNamedAndRemoveUntil works, the solution in my case was even more simple:

Make sure you're not Naming a route, which is not your Homescreen '/'.

Something like:

MaterialApp(
          title: 'Flutter Demo',
          initialRoute: Screen1.routeName,  // routeName = "/route1"
          routes: {
            Screen1.routeName: (ctx) => Screen1(),   // routeName = "/route1"
            Screen2.routeName: (ctx) => Screen2(),   // routeName = "/"
            Screen3.routeName: (ctx) => Screen3(),   // routeName = "/screen2"
          },
        );
      })

Will start your App with Screen1, but place Screen2 at the top of the Navigator's Stack.