简体   繁体   中英

How to navigate to previous page using device back button - Flutter

When I press the device back button, it navigate to the homepage but not to the previous page.

I would like to know how to navigate to the previous page using the the device back button.

Thank you

You might have used Navigator.pushReplacement which destroys the previous page and creates the new page.However if you use Navigator.push pressing the back button will navigate you to the previous screen.

Example:

Container(
        child: Center(
          child: TextButton(child: Text("Next page"),onPressed: (){
            Navigator.push(context, MaterialPageRoute(builder: (context) => Page2(),)); // back button will navigate to previous screen
            //Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Page2(),)); //  back button will not navigate to previous page
          },),),),

It was a Materialapp widget problem.

I solved the problem by deleting the Materialapp widget that was in one of the pages.

This occurs because the previous navigation was not saved in the route stack.

What you should do is this:

Widget A

Navigator.push(context, WidgetB());

Inside Widget B , press the device button and you will return to widget A.

It is important that in widget A you are not using replacement or another that removes widget A from the stack.

You can use:

Navigator.pop(context);

or

Navigator.pushNamed(context, '/routeName');

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