Sub topic 11
Running Code on Reload with State.reassemble
What you need first
This chapter assumes you can write a StatefulWidget and know the initState, build, and dispose lifecycle. It also assumes you have used hot reload and hot restart and know that hot reload keeps State objects alive. Earlier chapters explained why edits to initState do not show up after a reload. This chapter covers a hook that lets you handle that case.
What reassemble is
State.reassemble is a method on every State object. The framework calls it during a hot reload, once for each State object in the running widget tree. Its default implementation does nothing.
You override it when you want your code to run on each hot reload. Typical uses:
- Logging, to confirm that a reload reached a particular screen.
- Re-applying a value that you normally set once in
initState. - Rebuilding a helper object, such as a controller, that was configured with old values.
reassemble is a development tool. It is meant for the debug loop, not for application behavior.
Where it sits in a reload
During a hot reload, the tooling sends the changed source to the Dart VM. The VM swaps in the new code, and the tooling then asks the Flutter framework to reassemble the app. The framework walks the element tree. For each stateful element it calls State.reassemble first, and then marks the element as needing a rebuild.
Two consequences follow from this order:
reassembleruns beforebuild, so changes you make inreassembleare visible in the very next build.- If the VM rejects your edit, for example because of a compile error, the reassemble step never starts. No
reassemblecall means the reload did not happen.
Reassemble compared to other lifecycle methods
The table shows which State methods run for each kind of event.
| Event | `initState` | `reassemble` | `build` | Fields on `State` |
|---|---|---|---|---|
| `setState` call | No | No | Yes | Kept |
| Hot reload | No | Yes | Yes | Kept |
| Hot restart | Yes (new object) | No | Yes | Reset |
| Full restart | Yes (new object) | No | Yes | Reset |
On a hot restart, the app starts over with fresh State objects, so there is nothing to reassemble. Everything runs from main, including initState.
reassemble also differs from didUpdateWidget. The framework calls didUpdateWidget when a parent supplies a new widget configuration, and it does that in release builds too. reassemble is called on every State in the tree on every hot reload, whether or not that widget's own code changed.
Basic usage
The simplest use is a log line. The counter below keeps its count across reloads, and the log shows that the same State object is still there.
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
void reassemble() {
super.reassemble();
debugPrint('Hot reload happened, _count is still $_count');
}
@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),
),
);
}
}To try it:
- Run
flutter run. - Tap the button three times.
- Change the title text in
buildand pressrin the terminal.
The terminal prints Hot reload happened, _count is still 3, and the screen shows the new title with the count intact. If you press R instead, the log line does not appear, and the count goes back to 0.
Always call super.reassemble(). The method is marked as one that subclasses must call, and the analyzer warns you if you leave it out. Put the call first so any base-class work happens before yours.
Worked example: applying a changed value from initState
The most useful application of reassemble is fixing the "my initState edit is ignored" problem without a restart.
An AnimationController is created in initState with a duration. If you change the duration and hot reload, the controller already exists, so it keeps the old duration. The code below re-applies the duration on each reload.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: SpinnerPage()));
class SpinnerPage extends StatefulWidget {
const SpinnerPage({super.key});
@override
State<SpinnerPage> createState() => _SpinnerPageState();
}
class _SpinnerPageState extends State<SpinnerPage>
with SingleTickerProviderStateMixin {
// Edit this value, then press r.
Duration get _spinDuration => const Duration(seconds: 2);
late final AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: _spinDuration)
..repeat();
}
@override
void reassemble() {
super.reassemble();
// initState does not rerun on hot reload, so apply the duration again.
_controller
..duration = _spinDuration
..repeat();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RotationTransition(
turns: _controller,
child: const Icon(Icons.refresh, size: 96),
),
),
);
}
}Change seconds: 2 to seconds: 1 and press r. The icon spins faster right away. Without the reassemble override, you would need R.
The duration comes from a getter on purpose. A getter's body is part of the code that the VM replaces, so it returns the new value after a reload. A value stored in a field during initState would stay old.
Rules and gotchas
It runs on every State, every time
The framework does not check whether your widget's code changed. If your app has 40 stateful widgets on screen, you get 40 reassemble calls on each reload. Keep each override cheap, and make it safe to run many times in a row. Calling repeat() on an already repeating controller, as above, is safe. Opening a new network connection on every reload is not.
Do not call setState
A rebuild follows reassemble anyway, so setState adds nothing. Change fields directly and let the following build read them.
Do not put production logic in it
reassemble is a debug-time feature. It is not called in release builds, because hot reload does not exist there. Anything your app needs for correct behavior belongs in initState, didChangeDependencies, didUpdateWidget, or dispose. Use reassemble only to make development smoother.
It does not fix everything
reassemble can re-apply values you read from code, but it cannot change what the VM refuses to reload. Edits to main, to global variable initializers, and to static field initializers still need a hot restart. It also cannot give you a different generic type for an existing object, or change a class in a way the VM rejects. In those cases the tooling reports that a restart is needed.
Avoid hiding bugs
If you re-create state in reassemble, remember that a teammate running a hot restart or a release build will not get that behavior. Treat the override as a convenience that mirrors what initState already does. If the two diverge, you may chase bugs that only appear after a restart.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Log line never appears | The edit failed to compile, so no reload ran | Read the terminal for errors and fix them |
| Log line never appears after `R` | Hot restart does not call `reassemble` | Use `r` for reload, or log in `initState` too |
| Analyzer warns about `reassemble` | `super.reassemble()` is missing | Add `super.reassemble();` as the first line |
| Resources pile up during development | Override creates a new controller or subscription on each reload | Re-configure the existing object, or dispose the old one first |
| Value still old after reload | Value is read from a field set in `initState` | Read from a getter, or assign the field inside `reassemble` |
Summary of when to use it
Use State.reassemble when you are iterating on a value that lives in initState and you want a reload to apply it. Use it for logging when you need to confirm a reload reached a certain screen. For everything else, a normal hot reload or a hot restart is the simpler tool.
Exercise
You override reassemble in a State class and add a debugPrint line. You edit a string in build and press R (capital) in the terminal. Does the debugPrint line appear, and what happens to the State's fields? Explain why.
Show answer
The line does not appear. R triggers a hot restart, which discards the running widget tree and starts the app from main with new State objects. reassemble is only called on existing State objects during a hot reload, so it is never called. The fields are reset to their initial values, because initState runs again on the new State objects.
Exercise
A State class sets final Color _color = Colors.red in a field initializer and uses it in build. You change it to Colors.blue and press r. The screen stays red. Name two ways to make the new color appear, one without a restart and one with.
Show answer
Without a restart, replace the field with a getter (Color get _color => Colors.blue;) so build reads the new code on each call. A non-final field assigned inside reassemble also works. With a restart, press R, which creates a new State object so the field initializer runs again with the new value.