如何关闭(弹出)Flutter应用程序中的所有类似路由?

huangapple go评论74阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月11日 19:43:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76227275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定