Flutter Forms:多个小部件使用相同的 GlobalKey

Flutter Forms: Multiple widgets used the same GlobalKey

我看过很多关于这个问题的帖子,但 none 的答案对我的情况有效(我想我也知道为什么)。我的 Flutter 移动应用程序中有一个 着陆页 ,用户可以在其中 注册 登录 ,或者要求收到一封电子邮件以重置他们的密码。对于这些功能中的每一个,我都有一个 Form 小部件。每个表单都需要一个表单密钥(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.

现在 is similar but the solution doesn't work because I need the keys to be of the type GlobalKey, because they are form keys and I need to be able to call .validate(), for example. 非常相似,但解决方案也行不通。首先,OP 显示一个错误,其中两个小部件具有不同的描述;我的错误产生了具有相同描述的小部件。

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

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,因为页面被声明为最终页面并且每个页面仅使用其唯一键一次。感谢您的帮助!

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