Sub topic 1
Widgets, Elements and the tree Flutter keeps between frames
Prerequisites
This chapter assumes you can write a StatefulWidget, call setState, and build a Column or ListView. You should also know basic Dart syntax.
Three objects, three jobs
Flutter uses three kinds of objects to draw the screen:
- A widget is an immutable description of part of the UI. Flutter creates and discards widgets often, and they are cheap.
- An element is a long-lived object in the element tree. It links a widget to a position in the UI.
- A State object holds mutable data for a
StatefulWidget. It lives on that widget's element.
Each time Flutter rebuilds, it creates new widgets. It then compares them with the elements from the previous frame. If a match is found, the element and its State are reused. If not, they are discarded and new ones are created.
Where State lives
State belongs to the element, not the widget. The widget is replaced on every build, but the element stays in place as long as Flutter matches it. This is why a counter keeps its value when its parent rebuilds.
The matching rule
Flutter reuses an element only when the widget in the same position has:
- The same
runtimeType, and - The same
key. If neither widget has a key, both keys arenull, and they count as equal.
Without keys, position alone decides the match.
The problem: state stays behind when a list is reordered
The following tile owns a tap counter. The list shown below reverses its order without keys.
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++),
);
}
}
class TileList extends StatefulWidget {
const TileList({super.key});
@override
State<TileList> createState() => _TileListState();
}
class _TileListState extends State<TileList> {
List<String> _labels = ['A', 'B', 'C'];
@override
Widget build(BuildContext context) {
return Column(
children: [
for (final label in _labels) CounterTile(label: label),
TextButton(
onPressed: () =>
setState(() => _labels = _labels.reversed.toList()),
child: const Text('Reverse'),
),
],
);
}
}Tap tile A twice, then press Reverse. The State at position 0 keeps a count of 2, but it now displays label C. The counts appear to swap onto the wrong items because the State follows the position, not the label.
caption: How Flutter decides whether to reuse a State object. alt: A flowchart. A new widget first checks whether the old widget at its position has the same runtime type. If not, a new element and State are created. If yes, it checks whether the keys match. Matching keys reuse the element and State. Otherwise a new element and State are created.
Exercise
A Column holds two stateful counters, A (count 3) and B (count 0), with no keys. The list is reordered to B, then A. Which count does the widget at the first position show, and why?
Show answer
It shows 3. Flutter matches by position, so the State at the first position keeps its count of 3 and now displays label B. The count stays with the position, not the label.