Kayes
Kayes

Reputation: 592

Flutter navigation back to home screen

I have a flutter app that has the following drawer:

navigation drawer

Routes:

  1. Home: "/"
  2. Nearby: "/nearby"
  3. Applied: "/applied"

The behaviour I want to achieve is when the user clicks the android back button from nearby and applied screens, the app should take them to the home screen. If they press the back button from the home screen again it takes them out of the app.

Just to clarify here if they go to nearby, then to applied then click the back button it should take them to home, not applied.

Here is my code for navigating when nearby and applied drawer items are selected:

Navigator.pushNamedAndRemoveUntil(
    context, 
    routeName, 
    ModalRoute.withName("/")
);

I expected this to leave the following routes in the stack:

  1. home
  2. selected page

But what I am getting is from nearby or applied screen when I tap the back button on android it takes me out of the app, rather than drop me to the home screen.

What am I missing? How can I achieve the behaviour I'm looking for?

Note that I know there's a solution using WillPopScope widget but I am looking for a solution that uses the navigation stack. More importantly I'm interested to know why the above scenario is not working.

Upvotes: 5

Views: 9975

Answers (2)

Criss Gibran
Criss Gibran

Reputation: 104

Navigator.of(context).popUntil((route) => route.isFirst);

Upvotes: 4

Amon C
Amon C

Reputation: 1808

Add this WllPopCallBack() in NearBy and Apply widgets.

Future<bool> _willPopCallback() async {
     Navigator.pushNamedAndRemoveUntil(
    context, 
    routeName, 
    ModalRoute.withName("/")
);
    return false; // return true if the route to be popped
}

Add this WllPopScope widget over Scaffold() in NearBy and Apply widgets like this:

new WillPopScope(child: new Scaffold(), onWillPop: _willPopCallback)

Upvotes: 2

Related Questions