All 7 Flutter Widget Tree, Element Tree & BuildContext questions
More in Flutter Widget Tree, Element Tree & BuildContext
Advertisement
Flutter › Flutter Widget Tree, Element Tree & BuildContext

How does Flutter's key based widget reconciliation process actually work, and why do you genuinely sometimes need to explicitly provide a Key when working with a genuinely dynamic, reorderable list of widgets?

Intermediate

Answer

When Flutter rebuilds a given part of the widget tree, it needs to properly determine exactly which specific new widget instances genuinely correspond to which specific previously already existing elements, and by default it does this simply by comparing each widget's own specific type and its own current relative position within its immediate parent, which can genuinely become quite problematic and incorrect for a dynamic, reorderable list, where simply reordering the underlying list items without providing an explicit distinct Key for each one can cause Flutter to incorrectly and mistakenly associate an entirely wrong specific piece of existing widget state with the genuinely wrong new specific list item, and explicitly providing a stable, uniquely distinct Key, such as a ValueKey based on each item's own genuine unique identifier, properly and correctly fixes this exact same specific kind of state confusion issue.
ListView(
  children: items.map((item) => ListTile(
    key: ValueKey(item.id),
    title: Text(item.name),
  )).toList(),
)
Real-world example A reorderable task list assigns each individual task item a distinct ValueKey based on its own genuine unique task identifier, correctly and properly preventing a genuinely confusing bug where a specific task's own expanded or collapsed visual state would otherwise incorrectly and mistakenly follow its current specific list position rather than correctly and properly following that exact same specific individual task itself.

Common follow-ups: What is the specific practical difference between using a ValueKey, an ObjectKey, and a UniqueKey?;What actual specific symptom does a genuinely missing key typically produce within a dynamic reorderable list?