我见过很多关于这个问题的帖子,但是没有一个答案对我有效(我想我也知道为什么)。我有一个登陆页面在我的颤栗移动应用程序,用户可以注册,登录,或要求收到电子邮件,以获得他们的密码重置。对于这些特性,我都有一个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.现在这个问题是类似的,但是解决方案不起作用,因为我需要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,因为页面被声明为final,并且每个页面只使用它的唯一键一次。任何帮助都是非常感谢的!
发布于 2021-03-10 09:58:03
我自己解决了这个问题,方法是将表单放在Statefulwidgets中,而不是尝试使用某些提供者状态管理。应该意识到GlobalKey确实需要一个状态!
https://stackoverflow.com/questions/66401001
复制相似问题