简体   繁体   English

如何使用设备后退按钮导航到上一页 - Flutter

[英]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.您可能使用过Navigator.pushReplacement ,它会破坏前一页并创建新页面。但是,如果您使用Navigator.push ,则按下后退按钮会将您导航到上一个屏幕。

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.这是一个 Materialapp 小部件问题。

I solved the problem by deleting the Materialapp widget that was in one of the pages.我通过删除其中一个页面中的 Materialapp 小部件解决了这个问题。

This occurs because the previous navigation was not saved in the route stack.这是因为之前的导航没有保存在路由堆栈中。

What you should do is this:你应该做的是:

Widget A小部件 A

Navigator.push(context, WidgetB());

Inside Widget B , press the device button and you will return to widget A.小部件 B中,按下设备按钮,您将返回小部件 A。

It is important that in widget A you are not using replacement or another that removes widget A from the stack.重要的是,在小部件 A 中,您没有使用替换或其他从堆栈中删除小部件 A 的方法。

You can use:您可以使用:

Navigator.pop(context);

or或者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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