Flutter 路由问题和重复的 GlobalKey

Flutter Routing Issue and Duplicate GlobalKey

我在使用 Flutter 路由和小部件树中重复的 GlobalKey 时遇到问题。

我的应用执行以下操作:

Screen_A -> Screen_B -> Screen_C

在每种情况下,导航 (->) 都是通过以下方式完成的(其中 * 是 B 或 C):

Navigator.push(context, MaterialPageRoute(builder: (context) => Screen_*()));

然后我从 Screen_C -> Screen_A 导航到:

Navigator.pushAndRemoveUntil(context, 
    MaterialPageRoute(builder: (context) => Screen_A()), 
    (Route<dynamic> route) => false);

最后,我使用原始的 Navigator.push 方法从 Screen_A -> Screen_B 开始导航。我收到以下错误:

'package:flutter/src/widgets/will_pop_scope.dart':断言失败:第 135 行第 12 行:'route == ModalRoute.of(context)':不正确。

小部件库捕获到异常:在小部件树中检测到重复的 GlobalKey。

作为参考,Screen_B 是我通过以下方式定义 GlobalKey 的一种形式:

GlobalKey<FormState> formKey = GlobalKey<FormState>();

我不明白为什么会这样。它出现在我定义 GlobalKey 的地方以及我如何路由是正确的方法。 Navigator.pushAndRemoveUntil 不应该删除路由堆栈历史记录,从而删除 Screen_B 中的旧 GlobalKey 吗?

已解决:解决方案原来是其中 我放置了 GlobalKey 声明。我以前像这样在我的有状态小部件之外拥有它:

GlobalKey<FormState> formKey = GlobalKey<FormState>();
class Screen_B extends StatefulWidget { (etc.) }
class _Screen_B extends State<Screen_B > { (etc.) }

但是在将它移动到后,我的问题就解决了。像这样:

class Screen_B extends StatefulWidget { (etc.) }
class _Screen_B extends State<Screen_B > { 
    GlobalKey<FormState> formKey = GlobalKey<FormState>();
    (etc.) 
}

===== 此外,正如 ikerfah 上面提到的,使用 pushReplacement() 也可以从 Screen_A -> Screen_B -> Screen_C.