Flutter: How to push a navigation route without the back button?

Viewed 4165

I understand that Navigator.pushReplacementNamed allows you to replace the current screen on the back stack, but how do you handle cases where the current screen already has its own back button?

I've noticed if I use the .pushReplacementNamed function in this case, it retains the back button from the previous screen, but I would like to have this flow:

Screen A .pushNamed -> Screen B (able to navigate back to A) .pushReplacementNamed -> Screen C (should not be able to navigate back to either B or A)

3 Answers

If you are using an AppBar widget on the targetted screen, make sure you add this line inside your AppBar widget, which will prevent the app from automatically adding a back button by default on the AppBar :

    automaticallyImplyLeading: false,

But, either you use AppBar or not and you don't wanna go to the previous screen by clicking on the back button(physical button or Cupertino slide gesture), you have to use WillPopScope as the root widget on the target screen. Also, your onWillPop method should look like this:

onWillPop: () async => false,

by returning false, you are restricting your screen from leaving the screen and you can't exit the app now by clicking the back button. Because you are returning false as the decision if you want to go back or not. You can use exit(0) on this point inside the onWillPop method if you wish to close the app's new screen.

you should wrap root Widget with WillPopScope to be able handle back button

example below

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
  return new WillPopScope(
    onWillPop: () async => false,
    child: Scaffold(
      appBar: AppBar(
        title: Text("WillPopScope example"),
      ),
      body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                child: Text('Back'),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ],
          )
      ),
    ),
  );
}

}

Overriding back buttons might help you.

Please search for leading argument for appBar and WillPopScope

Related