
When Keys Matter: How Flutter Matches Widgets to Their State
- كاتب موثّق
- Flutter 3.x
محتويات المقال
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
find.byKey, a lint asks for a key parameter in every public widget constructor, and otherwise they never change how a widget behaves.
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
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.
It walks both lists from the top, pairing old elements with new widgets while they match. It does the same from the bottom. 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. Old elements that nothing claimed are removed, and their Stateobjects are disposed.
Why the expansion jumped
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.
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.
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)], ), ]); }}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( key: ValueKey(order.id), // state follows the order, not the row title: Text('Order ${order.id}'), children: [Text(order.summary)], ), ]); }}Pick the key from your data
ValueKey(order.id) | |||
ObjectKey(order) | |||
ValueKey(index) | |||
UniqueKey() | build(), it resets state on every build | ||
GlobalKey() | State | build() |
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
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:
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
Find the stateful items in dynamic lists Look 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,Checkboxanimations orDismissible.Key them from the data Use ValueKey(item.id). Avoid the index, and avoidUniqueKey()or newGlobalKeys created inbuild().Put the key on the outermost widget of each item If you wrap the item in Padding,CardorInkWell, the key belongs on the wrapper that sits in the list.Add findChildIndexCallback to builder lists that change order Map 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.builderalso needsfindChildIndexCallbackto keep state when items move.GlobalKeyis for moving a subtree or reaching itsState; create it once, never inbuild().
التعليقات (0)