简体   繁体   中英

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 ?

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);

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM