Sub topic 2
Reconciliation: reuse, update, or replace
This chapter assumes you know Dart classes, StatelessWidget and StatefulWidget, and common layout widgets such as Row, Column, Padding, and Text.
Reconciliation: reuse, update, or replace
Each time a widget builds, Flutter creates a new widget tree. Widgets are cheap, immutable descriptions, so Flutter compares the new description with the element that already exists at that position. An element is the long-lived object that owns a widget's state. For each child, Flutter checks Widget.canUpdate. If the runtime type and the key both match, the element keeps its place and receives the new widget. If either differs, Flutter unmounts the old element and mounts a new one.
Keys: keeping State attached to the right widget
Without a key, Flutter matches children by position. If a list reorders, each element gets a different widget, and any State stored in those elements stays where it was. A ValueKey tells Flutter which element belongs to which item, so the state moves with the item.
import 'package:flutter/widgets.dart';
void main() => runApp(const Directionality(
textDirection: TextDirection.ltr,
child: SwapDemo(),
));
class Tile extends StatefulWidget {
const Tile({super.key, required this.label});
final String label;
@override
State<Tile> createState() => _TileState();
}
class _TileState extends State<Tile> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _taps++),
child: Text('${widget.label}: $_taps'),
);
}
}
class SwapDemo extends StatefulWidget {
const SwapDemo({super.key});
@override
State<SwapDemo> createState() => _SwapDemoState();
}
class _SwapDemoState extends State<SwapDemo> {
List<String> _labels = ['A', 'B'];
@override
Widget build(BuildContext context) {
return Column(
children: [
GestureDetector(
onTap: () => setState(() => _labels = _labels.reversed.toList()),
child: const Text('swap'),
),
Row(
children: [
for (final label in _labels)
Tile(key: ValueKey(label), label: label),
],
),
],
);
}
}Tap A a few times, then tap "swap". The counter stays with its label. Remove the key argument and the counters stay in position while the labels change under them.
Where State lives and why it survives rebuilds
A State object belongs to its StatefulElement, not to the widget. Widgets are recreated on every build, but the element and its State persist as long as reconciliation keeps the element. A rebuild that reuses the element keeps the counter value. A rebuild that replaces the element creates a fresh State with its initial values.
Render objects: layout, painting, and hit testing
Only some widgets create render objects. Padding and Text do, because they must measure, draw, and respond to touches. StatelessWidget and StatefulWidget compose other widgets and create none. A render object (a RenderBox for most visual content) performs three jobs: it chooses its size within the constraints from its parent, paints itself, and answers hit tests for touch input.
What setState really does
setState runs your callback, then marks the element dirty. It does not rebuild immediately. Flutter rebuilds the dirty element during the next frame's build phase, then runs layout and paint only where needed.
Exercise
In the SwapDemo example, what happens if you change Tile(key: ValueKey(label), ...) to Tile(label: label) and tap "swap" after tapping A twice?
Show answer
Without a key, Flutter matches the first Tile element to the first label. The counter stays at position one, so it shows "B: 2" after the swap. The taps appear to move to the wrong label.