英文:
How to close (pop) all the similar routes in flutter application?
问题
在我的应用程序中,我有7个以上的屏幕。我正在使用命名路由。
screen1是默认的第一页。
当从screen4点击返回按钮时,我需要关闭screen4并转到screen3,此时路由树中有多个screen4(连续如1 2 3 4 4 4 4 4)。我希望一次关闭所有的screen4。
我尝试了下面的代码,但是上下文始终返回'screen4',所以它只关闭到screen2。
while (ModalRoute.of(context)!.settings.name == 'screen4' && Navigator.of(context).canPop()) {
if (mounted) {
Navigator.of(context).pop(true);
}
}
我需要将true传递给screen3,所以我不能在这里使用popuntil。
英文:
In my app I have 7+ screens. I am using named routes.
screen1 is default first page..
I have to close screen4 when tapping back button from screen4 and need to go screen3, in this case there are multiple screen4 there in route tree(back to back like 1 2 3 4 4 4 4 4 ). I want to close all the screen4 in one tap.
I tried below code but the context is always giving 'screen4' so it closing till screen2
while (ModalRoute.of(context)!.settings.name ==
'screen4' && Navigator.of(context).canPop()) {
if (mounted) {
Navigator.of(context).pop(true);
}
}
I need to pass true to screen3 so I can't use popuntil here
答案1
得分: 0
popuntil
仍然可以适用于您提到的情况:
Navigator.of(context)
.popUntil((Route route) => route.settings.name != 'screen4');
这将从
1 -> 2 -> 3 -> 4 -> 4 -> 4
变为
1 -> 2 -> 3
如果您有进一步的条件,请在popuntil
内应用它们。
英文:
popuntil
can still work for the scenario you mention:
Navigator.of(context)
.popUntil((Route route) => route.settings.name != 'screen4');
This will take you from
1 -> 2 -> 3 -> 4 -> 4 -> 4
to
1 -> 2 -> 3
if you have further conditions, apply them within popuntil
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论