Sub topic 5
What State Survives a Hot Reload
This chapter assumes you can read Dart, know the difference between StatelessWidget and StatefulWidget, and have run an app with flutter run. It explains which values a hot reload keeps, which it discards, and why. The rule comes from how the framework rebuilds the widget tree, so the chapter starts there.
The Core Rule
A hot reload does two things:
- The Dart VM loads the changed code and updates the class definitions in the running program. Existing objects stay in memory and now use the new method bodies.
- The framework marks the whole widget tree for rebuild, so every
buildmethod runs again with the new code.
Nothing in these steps throws away the objects that hold your state. Flutter keeps a long-lived element tree next to the widget tree. Each StatefulWidget has an element, and that element owns a State object. The widgets are short-lived configuration objects, and build creates new ones all the time. The State objects live as long as their elements do.
So the state that survives a hot reload is the state held by objects that the rebuild does not replace. Which State objects survive depends on whether the rebuild matches each new widget to the same element as before.
What Survives
Values stored in the following places keep their current values across a hot reload:
- Instance fields of a
Stateobject, such as_countin a counter. The object is the same, so the field is the same. - Objects those fields point to, such as a
TextEditingController, aScrollController, anAnimationController, or a list you built up at runtime. - Scroll position and text field contents, because the framework objects holding them sit in the preserved element and
Statetree. - The navigation stack. The
Navigatoris aStatefulWidget, so its route history stays, and you remain on the screen you were editing. - Global variables and static fields that have already been initialized. Their current values stay in memory.
- Objects outside the widget tree, such as singletons, caches, and open database connections, as long as a global or static field references them.
Here is a complete app you can use to test this. Run it, tap the button a few times, and then change the label in build.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: CounterPage()));
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(child: Text('Count: $_count')),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}After you change 'Count: $_count' to 'Taps: $_count' and hot reload, the label changes and the number stays. build ran again with new code, but _count lives in the same State object, so it was never touched.
What Does Not Survive
Hot reload keeps existing values. It does not recompute them. Code that only runs once, when an object is created, is not run again for objects that already exist. Two groups of values are affected.
Values set at creation time
initState runs once per State object, when the element is first mounted. A hot reload does not create a new State, so a changed initState never runs for the screen you are looking at.
class _CounterPageState extends State<CounterPage> {
late int _count;
@override
void initState() {
super.initState();
// Changing this value and hot reloading does not update an existing State,
// because initState already ran. A hot restart runs it again.
_count = 0;
}
@override
Widget build(BuildContext context) {
return Text('Count: $_count');
}
}If you change _count = 0 to _count = 100 and hot reload, the screen shows no change. The same applies to field initializers such as int _count = 0;. They run in the constructor of the State object, so editing the initial value has no effect on a State that already exists. The new value appears the next time a fresh State is created. A hot restart does this, and so does navigating away and back.
Globals and statics
Global variables and static fields keep the value they hold at the time of the reload. Editing their initializer does not re-run it.
// Global variable and static field initializers are not rerun by hot reload.
const greeting = 'Hello';
int globalCounter = 10;
class Config {
static int retries = 3;
}
void main() {
// Edits to main() are also not applied by hot reload.
runApp(const MaterialApp(home: Scaffold(body: Text(greeting))));
}If globalCounter has already been read or changed, setting its initializer to 20 does nothing until a hot restart. main is only called at startup, so edits to it are not applied either. Chapter material on "Changes Hot Reload Cannot Apply" covers these cases in full. Here the point is the pattern: state that was computed once stays as computed.
Summary Table
| Where the value lives | Survives hot reload? | Why |
|---|---|---|
| Field of an existing `State` | Yes | The `State` object is reused |
| `TextEditingController` held in `State` | Yes | Same object, same text |
| Scroll offset, navigator stack | Yes | Held by preserved elements |
| Local variable inside `build` | Recomputed | `build` runs again |
| Initial value in `initState` or a field initializer | Old value stays | Creation code is not re-run |
| Initialized global or static field | Old value stays | Initializer is not re-run |
| `State` whose position got a different widget type or key | No | Element is replaced, `State` is disposed |
When a State Is Lost Anyway
Even a plain hot reload can reset a screen. The reason is the matching rule in the diagram above. During rebuild, the framework compares the old widget at each position with the new one. It reuses the element only if both have the same runtimeType and the same key. Otherwise the old element is deactivated, its State is disposed, and a new one is created with initState and fresh field values.
You can trigger this with an edit that looks harmless. Suppose the counter is a separate widget, CounterBox, inside a page:
// Before the edit
body: Center(child: CounterBox()),
// After the edit: Padding now sits between Center and CounterBox
body: Center(
child: Padding(
padding: EdgeInsets.all(8),
child: CounterBox(),
),
),Under Center, the old child was a CounterBox and the new child is a Padding. The types differ, so the framework builds a new subtree and the counter goes back to zero. The reload worked correctly. Your edit changed the structure of the tree, and the framework treats that as a different widget.
Two other edits have the same effect:
- Changing a widget's
key, or adding or removing one where the old and new keys differ. - Changing which widget class sits at a position, for example replacing
CounterBoxwithCounterBoxV2.
Reordering children in a list that has no keys is a related trap. The framework matches children by position, so State objects stay at their positions while the data moves. Give list items keys such as ValueKey(item.id) so the State follows the item.
Edits That Change the Shape of State
A different problem appears when you change what a class is, not what a widget returns. Hot reload can add or remove methods and change method bodies. Existing objects were built with the old field layout, so some structural edits are rejected or need a restart. Examples include turning a StatelessWidget into a StatefulWidget, changing an enum to a regular class, and changing generic type arguments. Flutter prints a message saying a restart is needed. When this happens, nothing is applied, and your state is unchanged until you restart.
Adding a new instance field is the interesting case. Existing State objects were created before the field existed, so a non-late field with an initializer is set up in a way that depends on the VM version. Do not rely on the initial value of a newly added field appearing on a live screen. If the new field matters, hot restart.
Using the Preserved State on Purpose
Because the State object is the same one, you can observe a reload from inside it. State.reassemble is called on each hot reload, and the fields still hold their old values at that point.
class _CounterPageState extends State<CounterPage> {
int _count = 0;
@override
void reassemble() {
super.reassemble();
debugPrint('Hot reload happened, _count is still $_count');
}
@override
Widget build(BuildContext context) {
return Text('Count: $_count');
}
}Tap the button three times, then reload. The log reports _count as 3. That is a quick way to confirm whether a given State was kept. If the log shows 0 after you tapped, the State was replaced, and you should check for a type or key change above it.
Practical Habits
- Put values you want to tune live, such as colors, padding, and text, in
buildor in helper methods thatbuildcalls. They are recomputed on every reload. - Put values you want to keep, such as counters, form text, and selection, in
Statefields. They stay across reloads. - Avoid putting a tuning value only in
initStateor a field initializer. You will edit it and see nothing happen. - When you need a clean slate, use a hot restart instead of reloading repeatedly and wondering why the state is stale.
Exercise
A State class has the field int _score = 5; and a build method that shows 'Score: $_score'. You tap a button so _score becomes 8. Then you change the field initializer to int _score = 50; and change the label to 'Points: $_score', and hot reload. What does the screen show, and why?
Show answer
It shows "Points: 8". The new label is applied because build runs again with the new code. The initializer change is ignored because the existing State object was already constructed, so _score keeps its current value of 8. A hot restart would create a new State and show "Points: 50".
Exercise
A page contains Center(child: CounterBox()), where CounterBox is a StatefulWidget with a tapped count. You edit the page to Center(child: Padding(padding: EdgeInsets.all(8), child: CounterBox())) and hot reload. Does the count survive? Explain using the element matching rule.
Show answer
No, the count resets to 0. Under Center, the old child was a CounterBox and the new child is a Padding. The runtimeType differs, so the framework does not reuse the element. The old State is disposed and a new CounterBox element with a fresh State is created under the Padding.