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

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://api.flutter.dev/flutter/widgets/GlobalKey-class.html

解决方案

  1. 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]));
  2. 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());
  3. If using a GlobalKey for a form, store it in a map keyed by unique identifiers. Example: Map<String, GlobalKey<FormState>> formKeys = {};

无效尝试

常见但无效的做法:

  1. Remove the GlobalKey entirely from all widgets 70% 失败

    GlobalKeys are often needed for state preservation or form validation; removing them may break functionality.

  2. 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.