gpt4 book ai didi

flutter - Flutter 中 pushReplacementNamed 和 popAndPushNamed 的区别是什么?

转载 作者:行者123 更新时间:2023-12-04 09:35:46 24 4
gpt4 key购买 nike

NavigatorState类(class) Flutter#navigator.dart有2个具有类似行为的方法。 pushReplacementNamed有什么区别和 popAndPushNamed在 flutter 中?

pushReplacementNamed

Replace the current route of the navigator by pushing the route named [routeName] and then disposing the previous route once the new route has finished animating in.



popAndPushNamed

Pop the current route off the navigator and push a named route in its place.

最佳答案

如果您对数据结构有任何了解,那么您就会了解堆栈。如果您甚至对 stacks 有基本的了解,那么你就知道pushpop .

如果不这样做,推送是将元素添加到元素堆栈的顶部,而弹出是从同一堆栈中删除顶部元素。

所以在 Flutter 的情况下,当我们导航到另一个屏幕时,我们使用 push方法和 Navigator小部件将新屏幕添加到堆栈顶部。当然,pop方法将从堆栈中删除该屏幕。

所以让我们转到我们 Sample_Project 的代码库让我们看看如何从 Screen1 to Screen2 开始.您可以通过运行示例应用程序来试验这些方法。

new RaisedButton(
onPressed:(){
Navigator.of(context).pushNamed('/screen2');
},
child: new Text("Push to Screen 2"),
),

那很短。

那确实是。在 pushNamed 的帮助下方法,我们可以导航到任何在 main.dart 中定义了路由的屏幕。 .我们称他们为 namedRoute以供引用。这种方法的用例非常简单。简单地导航。

流行它

Stack after pushing Screen2

现在,当我们想要摆脱上次访问的屏幕时,即 Screen2在这种情况下,我们需要 pop使用 pop 方法从导航器的堆栈路由。
Navigator.of(context).pop();

请记住,这行代码在您的 onPressed 中。方法。

Stack after Screen 2 popped

使用 Scaffold 时,通常不需要显式弹出路由,因为 Scaffold 会自动在其 AppBar 中添加一个“后退”按钮,该按钮会调用 Navigator.pop()在按下。即使在 Android 中,按下设备的后退按钮也会做同样的事情。但是,对于其他用例,例如当用户单击“取消”按钮时弹出 AlertDialog,您可能需要此方法。

用例:pushReplacementNamed

当用户登录成功,现在在 DashboardScreen也许,那么你不希望用户回到 LoginScreen任何状况之下。所以登录路由应该完全被仪表板路由取代。另一个例子是去 HomeScreen来自 SplashScreen .它应该只显示一次,用户应该不能从 HomeScreen 返回到它。再次。在这种情况下,由于我们要进入一个全新的屏幕,我们可能希望使用此方法为其输入动画属性。

用例:popAndPushNamed

假设您正在构建一个购物应用程序,该应用程序在其 ProductsListScreen 中显示产品列表。并且用户可以在 FiltersScreen 中应用过滤器.当用户点击 Apply Changes按钮, FiltersScreen应该弹出并推回 ProductsListScreen使用新的过滤器值。这里是 popAndPushNamed的退出动画属性会看起来更合适。
pushReplacementNamed will execute the enter animation and popAndPushNamed will execute the exit animation.

Navigator.of(context).pushReplacementNamed('/screen4');
//and
Navigator.popAndPushNamed(context, '/screen4');

Stack before and after

更多 信息 访问本网站 Pooja_Bhaumik

关于flutter - Flutter 中 pushReplacementNamed 和 popAndPushNamed 的区别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59816770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com