Sub topic 4
Hot Reload: Applying Code Without Losing Your Place
This chapter assumes you can write basic Dart, build simple Flutter widgets, and tell a StatelessWidget from a StatefulWidget. It also assumes you can start an app with flutter run. Earlier chapters covered debug mode, the Dart VM, and how widgets and State objects relate. Here we look at what hot reload does to a running app, and what it leaves alone.
What Hot Reload Does
Hot reload sends your edited Dart source into the running app and rebuilds the UI with the new code. The app process keeps running. Existing State objects stay in memory, so fields such as a counter value, a scroll position, or text typed into a field are usually still there afterward.
A hot reload works in three steps:
- The tooling finds the Dart files that changed since the last compile.
- It compiles those files and sends them to the Dart VM running in your debug app. The VM swaps the new class and function definitions in place. Objects that already exist keep their field values and start running the new code.
- The Flutter framework tells every widget to rebuild, so
buildmethods run again with the new definitions.
Step 2 works because debug builds run on the Dart VM with just-in-time (JIT) compilation. The VM can accept new code while the program is running. Release builds are compiled ahead of time and have no such mechanism.
Seeing It Work
Run the counter app below, tap the button a few times, then edit the text passed to Text 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),
),
);
}
}Change 'Count: $_count' to 'Taps so far: $_count', then save the file in an IDE with reload-on-save, or press r in the terminal that runs flutter run. The label changes, and the number does not return to 0. The _CounterPageState object was never thrown away. Only its build method was replaced.
The terminal prints a line similar to this:
Performing hot reload...
Reloaded 1 of 612 libraries in 380ms.The library count tells you how many Dart files the VM had to update. A small edit touches one library, which is why reloads usually take well under a second.
Why the Whole Tree Rebuilds
Flutter does not try to work out which widgets your edit affected. After the VM finishes updating code, the framework runs a reassemble pass on the whole widget tree. Each State object's reassemble method is called, and every element is marked dirty, so every build runs again.
This has two consequences:
- Any edit inside a
buildmethod, however deep in the tree, shows up after one reload. - Rebuilding is cheap in Flutter, because
buildmethods should be fast and free of side effects. If abuildmethod does expensive work or has side effects, a reload will repeat that work, and you will notice it.
What Survives and What Does Not
The rule is simple: hot reload swaps code and leaves data alone. Code that already ran is not run again.
| Item | After a hot reload |
|---|---|
| Fields on an existing `State` object | Kept |
| Scroll positions, form text, selected tabs | Kept, because they live in existing `State` or controller objects |
| `build` method body | New code runs on the rebuild |
| Callbacks such as `onPressed` | Run the new code the next time they fire |
| Code in `initState` | Not rerun for existing `State` objects |
| `main()` | Not rerun |
| Global variables and static fields | Existing values kept, initializers not rerun |
The last four rows are where most confusion comes from. The next section explains the initState case. The remaining rows are covered in the chapter on changes hot reload cannot apply.
The initState Trap
initState runs once, when Flutter first creates a State object. Hot reload keeps that object, so the method never runs again for it.
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');
}
}Suppose you change _count = 0 to _count = 100 and reload. The screen still shows the old value, because _count was set when the State was created and nothing reset it. The new code is in the VM. A new State created later, for example by navigating to a fresh instance of the page, would run it. The existing object would not.
The same reasoning applies to anything set up once: controllers created in initState, subscriptions, and timers. If you edit how they are created, the old objects are still the ones in use.
Observing a Reload with reassemble
State.reassemble is a debug-only hook the framework calls on every State object during a hot reload. It lets you confirm that a reload happened and that your fields survived.
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');
}
}After tapping a few times and pressing r, the console prints the message with your current count. Always call super.reassemble() first. A later chapter returns to this hook as a development aid.
Changes That Make a Reload Fail or Mislead
Most edits reload cleanly, but a few kinds do not. Know them so you can tell a failure from a bug in your own code.
- Compile errors. If the edited file does not compile, the reload is rejected and the app keeps running the old code. The terminal shows the error. Fix it and reload again.
- Changing the kind of a widget. Turning a
StatelessWidgetinto aStatefulWidget, or the reverse, cannot be applied to existing objects. The tooling reports that a hot restart is needed. - Type-structure changes. Converting an enum to a class or a class to an enum, and changing generic type declarations, are rejected or need a restart.
- Native code. Edits to Kotlin, Java, Swift, Objective-C, or plugin native code are not Dart. A hot reload cannot apply them, and you need a full stop and run.
When a reload is rejected, the tool says so in the terminal and often suggests a hot restart. A reload that quietly shows no change is usually one of the "not rerun" cases from the table, such as initState, main, or an initializer.
A Practical Reload Routine
A workable habit during UI work:
- Run the app in debug mode with
flutter runor an IDE debug session. - Make a small edit, usually in a
buildmethod, and reload. - If the change appears, continue. If it does not, ask when the edited code runs. If it runs once at creation or at startup, reload cannot reach it.
- Use a hot restart for those cases. Later chapters compare restart and full restart in detail.
Small, frequent edits make this loop fast, and they make it easy to see which edit a reload rejected.
Summary Points
- Hot reload injects changed Dart code into the running VM and rebuilds the whole widget tree.
- It depends on debug mode and JIT compilation, so it is unavailable in release builds.
- Existing
Stateobjects, and the data in their fields, survive. - Code that runs once, such as
initState,main, and initializers of globals and statics, is not rerun for existing objects. - A successful reload message means the code was sent, not that every edit is visible.
Exercise
You run the counter app, tap the button until it shows 7, and change _count = 0; in initState to _count = 50;. You press r. What does the screen show, and why? What would you do to see 50?
Show answer
It still shows 7. Hot reload keeps the existing State object and its _count field, and it does not call initState again for that object. The updated initState code is in the VM but only runs for a State created after the reload. To see 50 right away, do a hot restart (R), which rebuilds the app from main and creates a new State.
Exercise
You add a debugPrint call inside State.reassemble and a second one inside initState. You press r three times. How many times does each message print, and what does that tell you about hot reload?
Show answer
The reassemble message prints three times, once per reload. The initState message prints no additional times, because the existing State object is kept. This shows that reload re-runs build-related code on the existing objects and does not re-create them.
Exercise
You edit a build method and press r. The terminal reports a successful reload, but the screen does not change. Name two likely causes.
Show answer
First, the edited value may come from code that does not rerun, such as an initState assignment, a global or static initializer, or something set in main. Second, the widget you edited may not be on screen or in the path that gets rebuilt, for example code on a route you have not opened. A compile error would show a rejection message, so it is not the cause here.