0

我看过很多关于这个问题的帖子,但在我的案例中没有一个答案有效(我想我也知道为什么)。我的Flutter 移动应用程序中有一个登录页面,用户可以在其中注册登录或要求获取电子邮件以重置密码。对于这些功能中的每一个,我都有一个Form小部件。每个表单都需要一个表单键 (a GlobalKey<FormState>)。借助IndexedStack. 在表单之间切换时收到的错误是:

The following assertion was thrown while finalizing the widget tree:
Multiple widgets used the same GlobalKey.

The key [LabeledGlobalKey<FormState>#eebb6] was used by multiple widgets. The parents of those widgets were different widgets that both had the following description:
  RegisterPage(dependencies: [_LocalizationsScope-[GlobalKey#f7403], _InheritedProviderScope<LandingPageModel>, _InheritedTheme])
A GlobalKey can only be specified on one widget at a time in the widget tree.

现在这个问题很相似,但解决方案不起作用,因为我需要键是 GlobalKey 类型,因为它们是表单键,.validate()例如我需要能够调用。这个问题非常相似,但解决方案也不起作用。一方面,OP 显示两个小部件具有不同描述的错误;我的错误产生具有相同描述的小部件。

我试图创建一个最小的代码示例,但错误并不完全相同。运行此代码段会产生类似的错误:

Duplicate GlobalKeys detected in widget tree.

The following GlobalKeys were specified multiple times in the widget tree. This will lead to parts of the widget tree being truncated unexpectedly, because the second time a key is seen, the previous instance is moved to the new location. The keys were:
- [LabeledGlobalKey<FormState>#a86c7]
  [LabeledGlobalKey<FormState>#c46a1]
  [LabeledGlobalKey<FormState>#1b7fd]
This was determined by noticing that after widgets with the above global keys were moved out of their respective previous parents, those previous parents never updated during this frame, meaning that they either did not update at all or updated before the widgets were moved, in either case implying that they still think that they should have a child with those global keys.
The specific parents that did not update after having one or more children forcibly removed due to GlobalKey reparenting are:
- ColoredBox(color: MaterialColor(primary value: Color(0xffff9800)), renderObject: _RenderColoredBox#8c966 relayoutBoundary=up6 NEEDS-PAINT)
  ColoredBox(color: MaterialColor(primary value: Color(0xff2196f3)), renderObject: _RenderColoredBox#73e9a relayoutBoundary=up6 NEEDS-PAINT)
  ColoredBox(color: MaterialColor(primary value: Color(0xff9e9e9e)), renderObject: _RenderColoredBox#dcb58 relayoutBoundary=up6)
A GlobalKey can only be specified on one widget at a time in the widget tree.

我不确定为什么它会给出不同的错误。原始代码对provider包做了一些工作,并且有LandingPage一个 StatelessWidget。无论如何,不​​应有重复的 GlobalKeys,因为页面被声明为最终页面,并且每个页面只使用其唯一键一次。任何帮助表示赞赏!

4

1 回答 1

1

我自己通过将表单放入 Statefulwidgets 而不是尝试使用某些提供程序状态管理来解决了这个问题。应该意识到 GlobalKey 确实需要一个状态!

于 2021-03-10T09:58:03.643 回答