Sub topic 2
Hot Restart: Resetting State Quickly
This chapter assumes you know basic Dart syntax, can build a StatefulWidget, and can run an app with flutter run or from an IDE. It also assumes you have already read about hot reload, which keeps state while applying code changes.
Hot Restart: Resetting State Quickly
Hot restart sends your changed code to the running Dart VM, then starts the app again without a full rebuild of the native shell. It discards every State object and runs main() again. Because of that, initState bodies and global or static initializers run again too.
Use hot restart when a change only takes effect after state is reset. The following example shows a case where hot reload leaves the old value in place.
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> {
late int _count;
@override
void initState() {
super.initState();
_count = 5; // Change this to 10, then hot restart.
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('Count: $_count')),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}Triggering Reload and Restart: r, R, and IDE Buttons
You can trigger each action from the terminal or from your IDE.
| Action | Terminal key | IDE control | Keeps state |
|---|---|---|---|
| Hot reload | r | Hot Reload button | Yes |
| Hot restart | R | Hot Restart button | No |
| Full restart | q, then run again | Stop, then Run | No |
flutter run
# In the terminal running flutter run:
# r -> hot reload
# R -> hot restart
# q -> quit, then run flutter run again for a full restartChanges Hot Reload Cannot Apply
Hot reload does not rerun main(), the body of initState for a State that already exists, or initializers for global and static non-const fields. Edits to those parts stay invisible until you hot restart.
Exercise
You change the starting value in initState from 5 to 10 and press r. The counter still shows the old value. What should you do, and why does it work?
Show answer
Press R to hot restart. Hot reload keeps the existing State object, so initState does not run again. Hot restart discards State objects and reruns initState, so the new value of 10 takes effect.