Sub topic 4
The problem: state stays behind when a list is reordered
This chapter shows a bug that appears when you reorder, insert or remove stateful widgets in a collection. You will reproduce it, then trace it through the Widget, Element and State objects to see why it happens. The fix comes in the next chapter. Here the goal is to predict the bug before you see it.
I assume you know these things from earlier chapters:
- Widgets are immutable descriptions, and Elements are the long-lived objects that sit in the tree.
- A
Stateobject is owned by aStatefulElement, not by the widget. - Flutter reuses an Element when the new widget has the same
runtimeTypeand the samekeyas the old one at that position.
A tile that owns state
The running example is a tile that counts taps. The label is data passed in by the parent. The count is state owned by the State object.
import 'package:flutter/material.dart';
class CounterTile extends StatefulWidget {
const CounterTile({super.key, required this.label});
final String label;
@override
State<CounterTile> createState() => _CounterTileState();
}
class _CounterTileState extends State<CounterTile> {
int _count = 0;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('${widget.label}: $_count'),
onTap: () => setState(() => _count++),
);
}
}The data is split in two places. label lives in the widget, which the parent recreates on every build. _count lives in the State, which survives rebuilds as long as its Element survives. This split is normal and useful, and it is also what makes the bug possible.
Reproducing the bug
The parent below holds a list of labels and a button that reverses the list. It builds one CounterTile per label and passes no key.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: TileList())));
class TileList extends StatefulWidget {
const TileList({super.key});
@override
State<TileList> createState() => _TileListState();
}
class _TileListState extends State<TileList> {
List<String> _labels = ['A', 'B', 'C'];
void _reverse() {
setState(() => _labels = _labels.reversed.toList());
}
@override
Widget build(BuildContext context) {
return Column(
children: [
for (final label in _labels) CounterTile(label: label),
TextButton(onPressed: _reverse, child: const Text('Reverse')),
],
);
}
}
class CounterTile extends StatefulWidget {
const CounterTile({super.key, required this.label});
final String label;
@override
State<CounterTile> createState() => _CounterTileState();
}
class _CounterTileState extends State<CounterTile> {
int _count = 0;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('${widget.label}: $_count'),
onTap: () => setState(() => _count++),
);
}
}Run it and follow these steps:
- Tap tile
Athree times. It showsA: 3. - Tap tile
Conce. It showsC: 1. - Press Reverse.
You would expect C: 1 at the top and A: 3 at the bottom. Instead you see C: 3, B: 0, A: 1. The labels moved, but the counters stayed where they were. Each count now sits under a label it was never tapped for.
Why it happens
Reordering the list changes the widgets, but Flutter decides what to reuse by looking at Elements and positions. Walk through the update step by step.
Before the reverse, the Column's child Elements hold these pairs:
| Position | Widget label | Element | State count |
|---|---|---|---|
| 0 | A | Element 0 | 3 |
| 1 | B | Element 1 | 0 |
| 2 | C | Element 2 | 1 |
After setState, the parent builds a new Column with children in the order C, B, A. For each position, Flutter asks whether the existing Element can be updated with the new widget. The test compares runtimeType and key:
- Position 0: the old widget is a
CounterTilewith no key. The new widget is aCounterTilewith no key. They match, so Element 0 is kept and receives the widget with labelC. - Position 1: same types, same null keys. Element 1 is kept and receives label
B. - Position 2: Element 2 is kept and receives label
A.
Flutter then calls didUpdateWidget on each State and rebuilds it. Each State now reads widget.label from the new widget, so the label changes. The _count field is untouched, because nothing told the State to reset it. The result:
| Position | Widget label | Element | State count |
|---|---|---|---|
| 0 | C | Element 0 | 3 |
| 1 | B | Element 1 | 0 |
| 2 | A | Element 2 | 1 |
State is attached to a position in the tree, not to the item you think of as "the tile for A". Without a key, position is the only identity Flutter has.
Why a stateless list does not show it
Replace CounterTile with a StatelessWidget that only displays its label. Reversing the list then looks correct, even though Flutter still reuses Elements by position. The Elements are reused and updated with new widgets, but all the data lives in the widgets, so the screen is right.
This is why the bug often goes unnoticed in early development. The list renders correctly until someone adds a field that the widget does not own, and then reordering exposes it. Reordering is the case that reveals the issue. The same position-based reuse is always happening.
Where the hidden state can be
The counter in this example is easy to see. In real apps the state that gets mixed up is often less obvious. Any of these can stay behind:
- Text typed into a
TextFieldorTextFormFieldinside each row. TheTextEditingControllerorEditableTextStatebelongs to the position. - A checkbox, switch or expansion tile that is open or closed, when it holds its own state.
- A running animation controlled by an
AnimationControllerin aState. - Focus. A
FocusNodecreated in aStatestays with that position. - A value you copied from the widget in
initState.
The last case produces a different symptom, and it is worth seeing because it is easy to misdiagnose. Suppose the State copies the label once:
class _CopiedLabelState extends State<CopiedLabelTile> {
late final String _label = widget.label; // Read once, never refreshed.
@override
Widget build(BuildContext context) {
return Text(_label);
}
}If the parent reorders such tiles without keys, the labels do not move at all. The list appears to ignore the reorder, because every State still holds its original label. The cause is the same position-based reuse, but nothing refreshes the cached value, since initState runs only once per State. Reading widget.label inside build, as CounterTile does, gives you the updated label but still leaves any other state behind.
Also note that a stateless widget can hide stateful widgets in its subtree. If a StatelessWidget row contains a TextField, the TextField has its own State. The row is reused by position, so the text field state stays by position too. You find the stateful widget by looking at the whole subtree, not only at the type you are reordering.
Other changes that trigger the same mix-up
Reversing is only one way to hit this. Any change that shifts which widget lands at which position can do it:
- Sorting. Sorting by name or date moves widgets relative to their old positions.
- Removing from the middle or front. Delete item
Afrom[A, B, C]. The new list is[B, C]. Position 0 reuses Element 0, which still hasA's state, and position 1 reuses Element 1. The last Element (position 2) has no matching new widget, so Flutter unmounts it and discards itsState. The state that disappears is the last one, not the one for the deleted item. - Inserting at the front. Insert
Zat the start of[A, B, C]. Elements 0 to 2 are reused forZ,A,B, and a new Element is created at position 3 forC. Every existing item gets a neighbor's state, and the newest state belongs to the last item. - Swapping two items. Only the swapped positions are affected, but those two exchange labels while keeping counts.
Appending to the end of a list is the one change that usually looks fine. Existing positions line up with existing Elements, and only a new Element is created at the tail.
Same type is the trigger
The mix-up requires that the old and new widgets at a position have the same runtimeType and the same key. If the types differ, Flutter does not reuse the Element. It disposes the old State and creates a new one. So a list that mixes different widget types, such as a header and a body that are never swapped with each other, does not suffer this problem at those positions. Lists of many items of one type are the high-risk case. They have the same type at every position, so every position matches.
A checklist for spotting it
Before you ship a list of stateful items that can change order, check these points:
- Is the collection built from data that can be sorted, filtered, reordered, or have items removed or inserted anywhere but the end?
- Does any widget in each item, at any depth, own a
State? Look forTextField,Checkbox,AnimationController,FocusNodeand your ownStatefulWidgets. - Do the items have the same widget type at the same level?
- Do the items have no key?
If all four are true, expect the behavior in this chapter. The test is easy: put a visible counter or a text field in each row, change the order, and see whether the content follows the label.
Exercise
A Column builds [CounterTile(label: 'A'), CounterTile(label: 'B'), CounterTile(label: 'C')] with no keys. The user taps A twice, B zero times and C five times, and then your code removes item A from the data list, so the Column now builds tiles for B and C. What labels and counts does the user see, and what happened to the State objects?
Show answer
The user sees B: 2 and C: 0. Position 0 reuses Element 0, which holds the State with count 2, and gets label B. Position 1 reuses Element 1, which holds count 0, and gets label C. The Element at position 2, which held count 5, has no matching widget, so it is unmounted and its State is disposed. The State that was lost belonged to C, not to the deleted item A.
Exercise
You change TileList so that the tiles are built from StatelessWidgets that only show a label, and reversing the list looks correct. Does that mean Flutter stopped reusing Elements by position? Explain why the display is correct.
Show answer
No. Flutter still reuses the Elements by position because the types match and there are no keys. The display is correct because a stateless widget keeps no data of its own. Everything shown comes from the new widget that each reused Element receives, so the labels follow the new order. The bug only appears when a State or a controller holds data that is not in the widget.