You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter应用中如何一次性关闭所有同名screen4路由?

解决Flutter多实例Screen4一次性返回Screen3并传值的问题

你之前的循环逻辑存在缺陷:当弹出最后一个Screen4后,Navigator.of(context).canPop()仍为true(此时可从Screen3返回Screen2),但ModalRoute.of(context)指向的是已被弹出的Screen4路由(context未同步更新),导致循环继续执行,最终多弹出一次到Screen2。

以下是可行的解决方案:先统计所有在Screen3之上的Screen4实例数量,再循环弹出对应次数,仅最后一次弹出时向Screen3传递true值:

// 统计需要弹出的screen4数量
int popCount = 0;
Route<dynamic>? currentRoute = ModalRoute.of(context);
while (currentRoute != null && currentRoute.settings.name != 'screen3') {
  if (currentRoute.settings.name == 'screen4') {
    popCount++;
  }
  currentRoute = currentRoute.parent;
}

// 执行弹出操作
NavigatorState navigator = Navigator.of(context);
for (int i = 0; i < popCount; i++) {
  if (mounted) {
    if (i == popCount - 1) {
      // 最后一次弹出,向screen3传递true
      navigator.pop(true);
    } else {
      // 弹出其余screen4,无需传值
      navigator.pop();
    }
  }
}

这段代码通过遍历路由的parent链,精准统计需要弹出的Screen4数量,避免了因context未更新导致的过度弹出问题,同时确保Screen3能正确接收到true参数。

内容的提问来源于stack exchange,提问作者Moony-Stary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:55:23