Sub topic 7
Reconciliation: reuse, update, or replace
Every rebuild produces a brand new set of widgets. Flutter does not redraw all of it. Reconciliation is the step that compares the new widgets with the existing elements and decides what to keep. This chapter explains that decision and the errors it causes when you misread it.
This chapter assumes you know basic Dart, can write StatelessWidget and StatefulWidget classes, and have read the earlier chapters on widgets and elements. You should know that a widget is an immutable description and an element is the long-lived instance that holds its place in the tree.
The problem reconciliation solves
When build runs again, it returns new widget objects. The old widget objects are still referenced by the existing elements. Flutter has two bad options:
- Throw away the old subtree and build a new one. This is correct but slow, and it destroys all State and render objects.
- Keep everything and ignore the new widgets. This is fast but shows stale UI.
Reconciliation is the third option. For each child slot, Flutter asks whether the existing element can represent the new widget. If it can, the element keeps its State and render object and takes the new configuration. If it cannot, that element is removed and a new one is created.
The canUpdate rule
The test is a single static method on Widget. It compares two things: the runtime type and the key.
// Paraphrase of the rule in Flutter's Widget class.
static bool canUpdate(Widget oldWidget, Widget newWidget) {
return oldWidget.runtimeType == newWidget.runtimeType &&
oldWidget.key == newWidget.key;
}Two points are easy to miss:
- It compares
runtimeType, notis. A subclass is a different type, so swappingTextfor a subclass ofTextreplaces the element. - Nothing else is compared. The fields of the widget, such as the string in a
Text, play no part. AText('a')replaced by aText('b')is an update, not a replacement.
When canUpdate is true, the element keeps its identity. It stores the new widget, and the next steps depend on the kind of element. A StatefulElement keeps its State object and calls didUpdateWidget on it. A RenderObjectElement calls updateRenderObject so the existing render object receives the new values.
What happens for a single child
Take an element whose widget builds one child, such as the result of a build method. The element calls an internal method, updateChild, with its current child element and the new widget. It has these outcomes:
| Existing child | New widget | Result |
|---|---|---|
| None | null | Nothing happens |
| None | A widget | A new element is created and mounted |
| An element | null | The old element is deactivated and removed |
| An element | A widget where `canUpdate` is true | The element is updated in place |
| An element | A widget where `canUpdate` is false | The old element is removed and a new one is created and mounted |
Replacement is the expensive case. The old element's State is disposed. Its render object is detached and discarded. Everything below it is rebuilt from scratch, because the new element has no children yet.
The diagram shows the decision for one child slot.
After an update, the process repeats for that element's own children. Reconciliation therefore walks down the tree. It stops early in some cases, for example when the new widget is the identical object as the old one (identical), which is why const widgets help. In that case Flutter skips the rebuild of that subtree unless something marked it dirty.
A concrete replacement example
Suppose a screen shows either a loading indicator or content, in the same position:
import 'package:flutter/widgets.dart';
class Switcher extends StatelessWidget {
const Switcher({super.key, required this.loading});
final bool loading;
@override
Widget build(BuildContext context) {
return loading ? const Text('Loading') : const Padding(
padding: EdgeInsets.all(8),
child: Text('Done'),
);
}
}When loading changes, the child slot holds a Text element and the new widget is a Padding. The types differ, so canUpdate is false. The Text element is removed and a Padding element is created. If both branches had the same type, such as two Text widgets, the element would be reused and only the string would change.
This matters most for stateful subtrees. If a StatefulWidget sits in one branch and a different type sits in the other, switching branches loses the State. If both branches contain the same stateful type in the same position, State carries over, which is sometimes a bug.
Multiple children
For widgets with a list of children, such as Row and Column, Flutter cannot simply compare slot to slot when the list changes. Its algorithm walks the old and new lists using both position and key:
- Match children from the start of both lists while
canUpdateis true. - Match children from the end of both lists the same way.
- For the middle section, build a map from key to old element for the old children that have keys.
- For each remaining new widget, use its key to find an old element in the map. If none matches, create a new element.
- Remove old elements that were not reused.
Children without a key can only be matched by position, in the head and tail passes. This is why a list of unkeyed stateful children behaves badly when you reorder it. Position decides identity, so the element at index 0 keeps its State even when a different widget now sits at index 0. The next chapter covers keys in detail. The ValueKey example in the topic's code samples shows the effect.
Errors and misconceptions
- Believing that changed fields cause replacement. Only type and key matter. Changing a color, a string, or a number updates the element.
- Expecting State to follow the data. State follows the element. If the element is matched by position, State stays at that position.
- Inserting a wrapper and losing State. Wrapping a stateful widget in a new parent, such as
Padding, changes the type at that slot. The old element is not reused, so its State is lost. Add wrappers consistently, or keep them stable across rebuilds. - Using a new key each build.
UniqueKey()created insidebuildnever equals the previous one, so the element is replaced on every rebuild. - Treating a rebuild as expensive. Creating widgets is cheap. The costly outcome is replacement, which discards elements and render objects and triggers new layout and paint work.
Observing it
You can see element reuse by putting a stateful child in a slot and changing only its configuration. If a counter keeps its value, the element was updated. If it resets to zero, the element was replaced. Compare this against a change of type at the same slot to see the reset.
Exercise
A Column contains Tile(label: 'A') and Tile(label: 'B'), both StatefulWidgets with no keys and each with its own tap counter. You reverse the list so that B comes first. What happens to the counters, and why?
Show answer
The counters stay at their positions and the labels change under them. With no keys, elements are matched by position. canUpdate is true for each slot because both widgets are Tile with a null key, so each element is updated with the new widget and keeps its State. Giving each Tile a ValueKey(label) makes the elements match by key, so each counter moves with its label.
Exercise
A slot builds a Text in one state and a subclass of Text, MyText, in another. Does the element get reused when the state changes? Why?
Show answer
No. canUpdate compares runtimeType, and MyText and Text are different runtime types. The old element is removed and a new one is created.