【发布时间】:2023-03-04 06:02:01
【问题描述】:
我看过很多关于这个问题的帖子,但没有一个答案在我的案例中有效(我想我也知道为什么)。我的 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.
现在this question 是类似的,但解决方案不起作用,因为我需要键为 GlobalKey 类型,因为它们是表单键,并且我需要能够调用 .validate(),例如。 This question 非常相似,但解决方案也不起作用。一方面,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,因为页面被声明为最终页面,并且每个页面只使用其唯一键一次。任何帮助表示赞赏!
【问题讨论】:
-
我认为原因可能是您将 GlobalKey 声明为全局变量,但您的小部件树中应该只有一个 GlobalKey。最好创建一个回调,在其中获取每个页面中表单的值并将其返回到您的 LandingPage() 小部件
-
但是我不能分别在每个表单上执行验证功能,对吗?
-
作为补充;删除全局定义的键并将
GlobalKey<FormState>作为参数直接传递给各个页面会导致相同的错误
标签: flutter dart flutter-form-builder