Sub topic 1
Why Hot Reload Exists: Debug Mode and the Dart VM
Prerequisites
You should know basic Dart syntax, how to build simple Flutter widgets, the difference between StatelessWidget and StatefulWidget, and how to start an app with flutter run or from an IDE.
Debug Mode and the Dart VM
In debug mode, a Flutter app runs on the Dart virtual machine (VM), which compiles code just in time (JIT). JIT means the code is turned into machine instructions while the app runs, so the VM can load new code into a live process. Release builds use ahead-of-time (AOT) compilation, which produces fixed machine code and cannot accept changes at runtime. Hot reload therefore exists only in debug mode.
The Development Loop with flutter run
Start the app with:
flutter runWhile it runs, press r in the same terminal to hot reload, R to hot restart, and q to quit. The tool stays connected to the VM and sends changed source files to the app.
Widgets, State Objects, and Rebuilds
A widget is an immutable description of part of the user interface. A StatefulWidget pairs with a State object, which lives longer than any single build. When setState runs, Flutter calls build again, and the State object keeps its field values. Hot reload tries to preserve these State objects.
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),
),
);
}
}Hot Reload: Applying Code Without Losing Your Place
Hot reload sends the changed source to the running VM, which loads it. Flutter then rebuilds the widget tree with the new code. Edit the text in build, save, and press r. The label changes, and _count keeps its value. The app does not restart.
What State Survives a Hot Reload
Hot reload keeps existing State objects and their field values. It does not rerun initState, main, or initializers for global and static variables. Changes to those need a hot restart or a full restart.
Exercise
In the counter example, you tap the button until _count is 5, then change the text in build and hot reload. What does the counter show?
Show answer
It shows 5. Hot reload keeps the existing State object and its _count field. Only build runs again, with the new text.