Sub topic 3
Widgets, State Objects, and Rebuilds
This chapter covers the framework mechanics behind hot reload: what a widget is, where a State object lives, and what a rebuild does. It assumes you can write basic Dart, build simple Flutter widgets, tell StatelessWidget from StatefulWidget, and run an app with flutter run or from an IDE. Later chapters on state preservation and reload limits depend on this model.
Widgets Are Short-Lived Descriptions
A widget is an immutable description of part of the user interface. It is not the thing on screen. Every field on a widget is final, and Flutter creates new widget objects constantly, usually many times per second during an animation.
Cheap widgets are what make this practical. Creating a Text('Count: 3') allocates a small object and does no drawing. The framework compares the new description with the previous one and changes only what differs.
Three kinds of objects work together:
| Object | Lifetime | Role |
|---|---|---|
| Widget | Short. Replaced on every rebuild. | Immutable configuration: "show this text in this color". |
| Element | Long. Lives while the widget stays at that position in the tree. | Holds the place in the tree, links the widget to its `State` and to the render objects. |
| State | Long. Created once per element of a `StatefulWidget`. | Holds mutable data and implements `build`. |
You rarely touch elements directly, but they explain why state survives rebuilds. The element is the permanent record of "something is displayed here". The widget is only the latest instruction for that record.
Where State Lives
A StatefulWidget is itself immutable. It exists to create a State object through createState. Flutter calls createState once, when the element is first inserted into the tree. From then on, the element keeps that State and repeatedly asks it to build.
The decision in the diagram is Widget.canUpdate. It compares the runtimeType and the key of the old and new widget. If both match, the existing element is reused and its State is kept. If either differs, the element and State are thrown away and replaced, and initState runs again on the new State.
Two consequences follow:
- A parent rebuilding does not reset its children's state, provided the children keep the same type, key, and position.
- Fields declared on the
Stateclass are the app's mutable data. Fields on the widget class are configuration passed down from the parent.
The State Lifecycle in Order
A State object moves through a fixed sequence:
createStatecreates the object.initStateruns once, when the object is inserted into the tree. Use it for one-time setup such as creating controllers or subscribing to streams.didChangeDependenciesruns afterinitState, and again when anInheritedWidgetthe state depends on changes.buildruns, and then again each time the element is marked dirty.didUpdateWidgetruns when the parent supplies a new widget instance of the same type and key.disposeruns once, when the element leaves the tree for good.
Only build (and didUpdateWidget, when the widget changes) repeats. initState does not. That one fact explains most hot reload surprises, and a later chapter uses it directly.
What Triggers a Rebuild
An element is rebuilt when it is marked dirty. The framework then rebuilds all dirty elements on the next frame. Three things mark an element dirty:
setState. The call runs your closure, then marks that state's element dirty. Mutating a field withoutsetStatechanges the data but does not schedule a rebuild.- A parent rebuild. When the parent's
buildreturns a new child widget, the element callsupdatewith it, and the child'sbuildruns again. A child created withconstand an identical instance can be skipped, because the framework sees the same object. - A dependency change. Widgets that read from an
InheritedWidget, such asTheme.of(context)orMediaQuery.of(context), rebuild when that inherited value changes.
Hot reload adds a fourth trigger. After new code is loaded, the framework runs a reassemble pass that marks the whole tree dirty. The next frame rebuilds every widget, using the new build code against the old State objects. That is why a reload shows your edit and keeps your data.
Observing Rebuilds in a Running App
The following app makes the model visible. A parent holds a color and a counter child. The parent's button rebuilds the parent. The child's button rebuilds only the child. Both log when they build.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ParentPage()));
class ParentPage extends StatefulWidget {
const ParentPage({super.key});
@override
State<ParentPage> createState() => _ParentPageState();
}
class _ParentPageState extends State<ParentPage> {
bool _warm = false;
@override
Widget build(BuildContext context) {
debugPrint('ParentPage build');
return Scaffold(
backgroundColor: _warm ? Colors.orange.shade100 : Colors.blue.shade100,
appBar: AppBar(title: const Text('Rebuild demo')),
body: Column(
children: [
TextButton(
onPressed: () => setState(() => _warm = !_warm),
child: const Text('Rebuild parent'),
),
const CounterTile(),
],
),
);
}
}
class CounterTile extends StatefulWidget {
const CounterTile({super.key});
@override
State<CounterTile> createState() => _CounterTileState();
}
class _CounterTileState extends State<CounterTile> {
int _count = 0;
@override
void initState() {
super.initState();
debugPrint('CounterTile initState');
}
@override
Widget build(BuildContext context) {
debugPrint('CounterTile build, count = $_count');
return TextButton(
onPressed: () => setState(() => _count++),
child: Text('Tapped $_count times'),
);
}
}Run it with flutter run, tap "Tapped 0 times" a few times, then tap "Rebuild parent". The console shows ParentPage build and the background color changes. The tile's count stays where it was, because the parent built a new CounterTile widget with the same type and key, so the old State was kept.
Note that CounterTile initState appears only once in the log, at startup. Because the tile is const with no changing arguments, the framework may skip rebuilding it when only the parent changes, so the CounterTile build line may not repeat after a parent tap. Whether a child rebuilds on a parent rebuild is an optimization, and your code should not depend on it either way.
Now edit the string 'Tapped $_count times' to 'Taps: $_count' and save. Press r in the terminal. The label changes, the count is unchanged, and initState does not print again. Every widget was marked dirty, the new build ran, and the same _count was read.
When Identity Changes and State Is Lost
State follows identity, and identity is type, key, and position among siblings. Changing any of these gives you a fresh State:
- Changing a widget's runtime type at the same position, such as replacing
CounterTilewith a different class, discards the old element. - Changing a key discards the element too.
ValueKey(1)andValueKey(2)are different keys. - Reordering siblings without keys can move state to the wrong widget. Flutter matches unkeyed siblings by position, so the first
Statestays with the first slot even if the data moved.
This applies to hot reload as well. If you edit the code in a way that changes the widget type at a position, that part of the tree gets a new State and starts from initial values, even during a reload.
Why `initState` Edits Are Not Picked Up
Hot reload replaces the code of classes, so the next call to build runs your new version. Methods that already ran are not run again. initState ran when the element was inserted, and a reload does not insert the element a second time. Editing the body of initState therefore has no visible effect on a State that already exists.
The same reasoning covers field initializers on a State class. A field such as int _count = 0; is evaluated when the State object is constructed. Changing it to 10 and reloading leaves the live object at its current value. Only a hot restart, which discards every State and builds the tree again, constructs new objects and applies the new initial value. The next chapters work through this in detail.
Common Errors
- Mutating without
setState. The field changes, but nothing rebuilds until something else marks the element dirty. A later hot reload may then appear to "fix" it, which hides the bug. - Putting setup in
build.buildcan run many times per second, and a reload runs it too. Creating controllers or starting timers there leaks resources and resets behavior on every rebuild. - Assuming a rebuild resets a child. A child with the same type and key keeps its
Statethrough any number of parent rebuilds. - Expecting
initStateto rerun on reload. It runs once perStateobject. Move one-time logic you want to tweak intobuild-driven code, or use a restart. - Missing
dispose. Controllers, focus nodes, and subscriptions created ininitStateneed cleanup indispose. Hot reload keeps theState, so they stay alive and are not recreated.
Summary of the Model
Widgets are disposable descriptions. Elements are the permanent positions in the tree. State objects hang off elements and hold your mutable data. A rebuild asks existing State objects to run build again and produces new widgets. A hot reload swaps the code and forces that same rebuild across the whole tree. Because the State objects are kept, your data survives. Because initState and field initializers do not rerun, edits to them do not show.
Exercise
In the demo app, you change the initState of _CounterTileState to set _count = 5 and press r. The tile still shows the old count. Why, and what action makes the new initial value appear?
Show answer
Hot reload keeps the existing State object, and initState already ran when that object was inserted into the tree, so it does not run again. A hot restart (R) discards all State objects and rebuilds the tree from main, which constructs a new _CounterTileState and runs initState with the new value.
Exercise
A list of unkeyed CounterTile widgets is built from a List<String>. You remove the first item from the list and rebuild. Which items keep which counts, and how would you fix the mismatch?
Show answer
Flutter matches unkeyed siblings by position, so each remaining State stays in its slot. The last slot's element is removed, and the counts end up attached to the wrong data items. Give each tile a stable key, such as ValueKey(item) or ValueKey(item.id), so the framework matches each State to its own item.