الانتقال إلى المحتوى
تطبيقات الموبايلFlutter· 7 دقائق للقراءة

When Keys Matter: How Flutter Matches Widgets to Their State

Without a key, state belongs to a position in the list, not to your data: remove one row and it moves to the next.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Flutter 3.x
محتويات المقال

An orders screen lists each order as an ExpansionTile. A support agent expands order 1042 to read the details. A refresh arrives, the cancelled order 1041 above it disappears, and now order 1043 is expanded while 1042 is collapsed. Nobody on the team wrote a StatefulWidget for this screen, so "state" isn't even on the list of suspects.

The common misconception

The belief: keys are optional IDs. They help a widget test find something with find.byKey, a lint asks for a key parameter in every public widget constructor, and otherwise they never change how a widget behaves.

Most of the time, that matches experience. A widget that's the only child of another widget generally doesn't need a key, as the Widget.key docs say, and static lists work fine without them. The half-truth is real: a key never changes what a widget looks like. What it changes is invisible until the list changes, and Flutter's own Dismissible makes the key a required argument for exactly that reason: without it, the item after a dismissed one would be synced with the dismissed item's state.

What actually happens

Elements are matched among siblings, in order

When a parent rebuilds, Flutter has to pair its new list of child widgets with its existing child elements. The keeps the State, so this pairing decides which state each new widget gets. An old element can take a new widget only if both have the same runtimeType and the same . Two widgets without keys have equal keys, both null, so by default the docs say widgets are matched by type and by the order in which they appear.

For a list of children, the framework works roughly like this:

  1. It walks both lists from the top, pairing old elements with new widgets while they match.
  2. It does the same from the bottom.
  3. In the middle that's left, it finds old elements by key wherever they were. An old element without a key there is not reused.
  4. Old elements that nothing claimed are removed, and their State objects are disposed.

The framework's own source comments sum it up: a widget with a key that's in both lists will be synced; widgets without keys might be, with no guarantee.

Why the expansion jumped

The old list was 1041, 1042, 1043; the new one is 1042, 1043. All three are ExpansionTile widgets without keys, so the walk from the top matches everything by position: the first element, collapsed, gets the widget for 1042. The second element, expanded, gets the widget for 1043. The third element is removed. The data moved up one row; the state didn't.

And that state was there all along. ExpansionTile is a StatefulWidget that keeps whether it's expanded in its own State, just as a TextField keeps typed text when you don't pass a controller. You don't have to write a State class to have one in your list.

Dart order_list.dart
class OrderList extends StatelessWidget {  const OrderList({super.key, required this.orders});  final List<Order> orders;  @override  Widget build(BuildContext context) {    return Column(children: [      for (final order in orders)        ExpansionTile( // matched by position: state stays at the index          title: Text('Order ${order.id}'),          children: [Text(order.summary)],        ),    ]);  }}

In a widget test with three orders, expanding 1042 and then removing 1041 left 1043 expanded in the first version. In the second, 1042 stayed expanded.

Pick the key from your data

KeyEqual to another key whenUse it forWatch out
ValueKey(order.id)The values are equalItems with a stable id: the usual choiceIds must be unique among siblings
ObjectKey(order)It's the same objectItems without an id, kept as the same instancesA refetch creates new objects, so state resets
ValueKey(index)The positions are equalNothing in a changing listBehaves like no key when a row is removed
UniqueKey()Never, except itselfForcing a fresh element on purposeCreated in build(), it resets state on every build
GlobalKey()It's the same key objectMoving a subtree to a new parent, reaching its StateRelatively expensive; never create one in build()

Keys only have to be unique among the children of one parent; two siblings with the same key fail with Duplicate keys found. A must be unique across the whole app. When a widget with a global key moves to a new place in the same frame, Flutter moves its element and subtree there instead of rebuilding them, which the docs call relatively expensive. A State should create it once, in initState or as a field, never inside build().

The key goes on the outermost widget of each item

Matching happens among the direct children of one parent. If each item is a Padding wrapping the ExpansionTile, the Padding widgets are the siblings, and they're still matched by position. A key on the inner tile then only makes it mismatch the tile it lands next to: in the same test, 1042 collapsed and nothing was expanded. Put the key on whatever widget sits directly in the list.

Lazy lists need one more step

ListView.builder creates children by index, and its docs warn that without a findChildIndexCallback a child may not map to its existing render object when the order changes, which may result in state loss:

Dart order_list_view.dart
Widget buildOrders(List<Order> orders) => ListView.builder(      itemCount: orders.length,      // Lets a keyed item find its old element at a new index      findChildIndexCallback: (key) {        final i = orders.indexWhere((o) => ValueKey(o.id) == key);        return i < 0 ? null : i;      },      itemBuilder: (context, i) => ExpansionTile(        key: ValueKey(orders[i].id),        title: Text('Order ${orders[i].id}'),        children: [Text(orders[i].summary)],      ),    );

How to apply it in your project

  1. Find the stateful items in dynamic listsLook for lists whose items can be inserted, removed or reordered and that hold any state: yours, or a framework widget's such as ExpansionTile, TextField, Checkbox animations or Dismissible.
  2. Key them from the dataUse ValueKey(item.id). Avoid the index, and avoid UniqueKey() or new GlobalKeys created in build().
  3. Put the key on the outermost widget of each itemIf you wrap the item in Padding, Card or InkWell, the key belongs on the wrapper that sits in the list.
  4. Add findChildIndexCallback to builder lists that change orderMap the key back to the item's new index, and write a widget test that removes the first item and checks the second keeps its state.

Key takeaways

  • A key decides which element, and so which State, a new widget is matched with; it never changes how it looks.
  • Without keys, siblings of the same type are matched by position, so state stays at an index.
  • Use stable keys from your data (ValueKey(id)), on the outermost widget of each item.
  • ListView.builder also needs findChildIndexCallback to keep state when items move.
  • GlobalKey is for moving a subtree or reaching its State; create it once, never in build().

📚 المصادر

  1. Introduction to widgets: Keys — Flutter docs
  2. Key class — Flutter API
  3. Widget.key — Flutter API
  4. GlobalKey class — Flutter API
  5. ListView.builder constructor — Flutter API

التعليقات (0)