flutter
runtime_error
ai_generated
true
在小部件树中检测到重复的 GlobalKey:GlobalKey#abcde 被多个小部件使用
Duplicate GlobalKey detected in widget tree: GlobalKey#abcde was used by multiple widgets
ID: flutter/global-key-duplicate-reparent
90%修复率
86%置信度
1证据数
2023-07-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Flutter 3.10.0 | active | — | — | — |
| Dart 3.0.0 | active | — | — | — |
根因分析
同一个 GlobalKey 被分配给了同一小部件树中的多个小部件,通常是由于列表或条件渲染中不当的键重用。
English
A GlobalKey is assigned to more than one widget in the same widget tree, often due to improper key reuse in lists or conditional rendering.
官方文档
https://api.flutter.dev/flutter/widgets/GlobalKey-class.html解决方案
-
Ensure each widget has a unique GlobalKey by generating a new key per instance. Example: ListView.builder(itemBuilder: (context, index) => MyWidget(key: GlobalKey(), data: items[index]));
-
Use ValueKey or ObjectKey instead of GlobalKey if state preservation is not required for every widget. Example: ListView(children: items.map((item) => MyWidget(key: ValueKey(item.id))).toList());
-
If using a GlobalKey for a form, store it in a map keyed by unique identifiers. Example: Map<String, GlobalKey<FormState>> formKeys = {};
无效尝试
常见但无效的做法:
-
Remove the GlobalKey entirely from all widgets
70% 失败
GlobalKeys are often needed for state preservation or form validation; removing them may break functionality.
-
Use a static GlobalKey variable shared across widgets
80% 失败
A static key is still a single instance; if used in multiple widgets, it will cause the same duplicate error.