Sub topic 4
The problem: state stays behind when a list is reordered
This chapter assumes basic Dart, StatelessWidget and StatefulWidget, Column, ListView, ListTile, and setState. The goal is to understand why a stateful list item can display the wrong state after its position changes.
State belongs to an Element
Flutter maintains several related trees:
- A Widget is an immutable description of part of the interface.
- An Element is Flutter's persistent location in the widget tree.
- A State object stores mutable data for a
StatefulWidget.
When build runs again, Flutter usually creates new widget objects. It does not automatically create new elements or state objects. Instead, Flutter compares the new widget with the widget that occupied the same location in the previous frame.
If Flutter reuses the existing element, its State also remains. If Flutter cannot match the old element, it removes that state and creates a new one.
With unkeyed widgets, the counter state from position 0 is reused for the new widget at position 0. The state follows the position, not the label.
Reproduce the reorder problem
The following complete example creates three stateful tiles. Tap the tiles to give them different counts, then press Reverse.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: TileList()));
}
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++),
);
}
}
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 Scaffold(
appBar: AppBar(title: const Text('Reorder problem')),
body: Column(
children: [
for (final label in _labels)
CounterTile(label: label),
TextButton(
onPressed: _reverse,
child: const Text('Reverse'),
),
],
),
);
}
}Suppose the counters are:
- A: 2
- B: 5
- C: 1
After reversing the labels, the screen can show:
- C: 2
- B: 5
- A: 1
The CounterTile objects for C and A are new widget configurations, but both have the same runtime type as the widgets previously in those positions. Since neither widget has a key, both old and new keys are null. Flutter therefore reuses the elements by position.
The State objects did not swap. Their labels changed because widget now refers to a different CounterTile configuration. The state that counted A is now being displayed with label C.
Why rebuilding does not fix it
Calling setState rebuilds the parent and produces a new list of child widgets. It does not tell Flutter that two items represent different logical entities. The matching process still sees three CounterTile widgets in the same three positions.
This behavior is efficient for ordinary static layouts. Flutter can update descriptions while preserving expensive elements and state. For dynamic collections, however, the application must provide a stable identity for each item. A key supplies that identity and lets Flutter match an item with its previous element when its position changes.
Keys solve this particular mismatch. Other state-preservation techniques, such as keeping a lazy child alive or lifting its state into the parent, address different lifecycle problems.
Exercise
A list displays items A, B, and C. Item A has a count of 3. The list is reversed without keys. Which count does the item now labeled C display, and why?
Show answer
It displays 3 because Flutter reuses the element and State at position 0. Without a key, the state follows the position instead of the logical item.