princeoo7
princeoo7

Reputation: 1121

Navigator PushReplacementName gives back button in flutter

This is weird but below code is not working for me. I get a back arrow on the home screen when using below code.

First line below is for dismissing the dialog box. second one is to go to home screen.

 Navigator.of(context, rootNavigator: true).pop();
 Navigator.of(context).pushReplacementNamed(HomeScreen.id);

This is first time I am facing this kind of situation with pushReplacementNamed. what's going on here ?

Upvotes: 1

Views: 1313

Answers (2)

It is probably because you have another screen in the stack. When you call pushReplacementNamed, it doesn't replace whole stack with the one you give. Can you try the following code;

// true don't work based on above query condition Navigator.of(context).pushNamedAndRemoveUntil(HomeScreen.id, (Route<dynamic> route) => true);

// false works Navigator.of(context).pushNamedAndRemoveUntil(HomeScreen.id, (Route<dynamic> route) => false);

Upvotes: 2

lordvidex
lordvidex

Reputation: 4098

That won't give the required result as you have already even popped the context away before calling another Navigator class. I tried the function Navigator.of(context).pushNamedAndRemoveUntil() but still got my HomeScreen pushed on stack twice with the back button on screen 1. Hence, I finally got this with the inbuilt function Navigator.of(context).popUntil(). You can run this dartpad code https://dartpad.dev/a10ed43452736b5c6b3d1abe6a7eda45 to view the desired effect or view the code below. Below is part of the code from the gist:

...
class ThirdPage extends StatelessWidget{
  static const routeName = '/third';
  @override
  Widget build(BuildContext context){
    void _nextPage(){
      //Logic here - ***************************
   Navigator.of(context).popUntil((Route<dynamic> route) => route.isFirst);
  }
    return Scaffold(
      appBar: AppBar(
        title: Text('Third Page'),
      ),
      body: Center(
        child: Text('Third Page'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _nextPage,
        child: Icon(Icons.add),
      ),
    );
  }
}

Happy coding D:)

Upvotes: 0

Related Questions