flutter runtime_error ai_generated true

Duplicate GlobalKey detected in widget tree: GlobalKey#abcde was used by multiple widgets

ID: flutter/global-key-duplicate-reparent

Also available as: JSON · Markdown · 中文
90%Fix Rate
86%Confidence
1Evidence
2023-07-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Flutter 3.10.0 active
Dart 3.0.0 active

Root Cause

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

中文

同一个 GlobalKey 被分配给了同一小部件树中的多个小部件,通常是由于列表或条件渲染中不当的键重用。

Official Documentation

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

Workarounds

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

中文步骤

  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 = {};

Dead Ends

Common approaches that don't work:

  1. Remove the GlobalKey entirely from all widgets 70% fail

    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% fail

    A static key is still a single instance; if used in multiple widgets, it will cause the same duplicate error.