Sub topic 14
Common mistakes with state
This chapter assumes you can write a StatelessWidget and a StatefulWidget, call setState, and use initState and dispose. It also assumes you know what lifting state up means. Here you will see the errors that come up most often in real code, why each one happens, and how to fix it.
Mistake 1: changing state without setState
Flutter does not watch your fields. A State object only rebuilds when you call setState. If you change a field and skip the call, the value changes in memory but the screen stays the same.
import 'package:flutter/material.dart';
class BrokenCounter extends StatefulWidget {
const BrokenCounter({super.key});
@override
State<BrokenCounter> createState() => _BrokenCounterState();
}
class _BrokenCounterState extends State<BrokenCounter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return ElevatedButton(
// Bug: _count changes, but no rebuild is scheduled.
onPressed: () => _count++,
child: Text('Count: $_count'),
);
}
}The fix is to wrap the change in setState(() { _count++; }). The callback passed to setState must be synchronous. Do the mutation inside it, and do slow work (network calls, parsing) before it.
A related trap is mutating a list or map in place and expecting children to notice. A child that compares old and new values with == sees the same object and may skip work. When you pass collections down, create a new one ([...items, newItem]) instead of changing the old one.
Mistake 2: calling setState during build
build must be free of side effects. If you call setState inside build, Flutter asks for a rebuild while it is already rebuilding. In debug mode you get an error such as "setState() or markNeedsBuild() called during build".
Typical causes:
- Calling a parent's callback directly in
build, for exampleonChanged(value)instead of passing it to a handler. - Writing
onPressed: _increment()instead ofonPressed: _increment. The first form runs the function during build and passes its result. The second passes the function itself.
If you need to run something once after the first frame, do it in initState or with WidgetsBinding.instance.addPostFrameCallback.
Mistake 3: creating long-lived objects in build
build can run many times per second during an animation. Anything you create there is created again each time. Controllers are the usual victim.
import 'package:flutter/material.dart';
class BadField extends StatelessWidget {
const BadField({super.key});
@override
Widget build(BuildContext context) {
// Bug: a new controller on every rebuild. Typed text and the
// cursor position are lost, and nothing disposes the old ones.
final controller = TextEditingController();
return TextField(controller: controller);
}
}Create the controller once in initState and release it in dispose, as in the NameField example from the lifecycle chapter. The same rule applies to AnimationController, ScrollController, FocusNode, StreamSubscription, and Timer. A good habit is to write the dispose line at the same moment you write the creation line.
Mistake 4: forgetting dispose
A missing dispose does not crash right away. The controller keeps its listeners alive, a timer keeps firing, or a stream subscription keeps delivering events to a widget that is gone. The result is memory growth and strange behavior later.
Follow these rules:
- Dispose everything you create in
initState, in the same class. - Call
super.dispose()last, after your own cleanup. - Call
super.initState()first ininitState.
Do not dispose objects you received from a parent. The parent created them, so the parent disposes them.
Mistake 5: setState after the widget is gone
Asynchronous work can finish after the user has left the screen. If the State was already disposed, calling setState throws an error saying it was called after dispose().
import 'package:flutter/material.dart';
class QuoteLoader extends StatefulWidget {
const QuoteLoader({super.key});
@override
State<QuoteLoader> createState() => _QuoteLoaderState();
}
class _QuoteLoaderState extends State<QuoteLoader> {
String _quote = 'Loading...';
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
await Future<void>.delayed(const Duration(seconds: 2));
// The user may have left the screen during the delay.
if (!mounted) return;
setState(() {
_quote = 'Loaded';
});
}
@override
Widget build(BuildContext context) {
return Text(_quote);
}
}mounted is true while the State is in the tree. Check it after every await before you call setState. Use the same check before using context after an await, for example before Navigator.of(context) or ScaffoldMessenger.of(context). The BuildContext can belong to a widget that no longer exists.
Where you can, cancel the work in dispose instead of only checking mounted. Cancelling a timer or subscription stops wasted work as well as the error.
Mistake 6: copying widget values into state and never updating them
When you copy a constructor argument into a field in initState, the copy is made once. If the parent later rebuilds with a different value, State is reused and your copy is stale.
import 'package:flutter/material.dart';
class SyncedLabel extends StatefulWidget {
const SyncedLabel({super.key, required this.title});
final String title;
@override
State<SyncedLabel> createState() => _SyncedLabelState();
}
class _SyncedLabelState extends State<SyncedLabel> {
late String _shown;
@override
void initState() {
super.initState();
_shown = widget.title;
}
@override
void didUpdateWidget(SyncedLabel oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.title != widget.title) {
_shown = widget.title;
}
}
@override
Widget build(BuildContext context) {
return Text(_shown);
}
}Without didUpdateWidget, the label would show the first title forever. Often the better answer is to not copy at all and read widget.title in build. Copy only when the State needs its own editable version, such as a text field that starts from an initial value. Do not call setState inside didUpdateWidget. A rebuild is already coming.
Mistake 7: storing derived data as state
If a value can be computed from other state, compute it. Storing both creates two sources of truth that can drift apart.
// Fragile: _items and _total must always be updated together.
List<double> _items = [];
double _total = 0;
// Better: one source of truth, and a getter.
double get _totalPrice => _items.fold(0.0, (sum, p) => sum + p);Only store the minimum: the list. Anything you can derive (a total, a filtered list, an "is empty" flag) belongs in a getter or a local variable inside build. If the computation is expensive, measure first before caching it.
Mistake 8: putting state at the wrong level
State that sits too low forces awkward workarounds. State that sits too high rebuilds more than it should.
| Symptom | Likely cause | Fix |
|---|---|---|
| Two sibling widgets must show the same value but disagree | Each owns its own copy | Lift the value to the nearest common parent |
| Whole screen rebuilds when one small toggle changes | State lives in the screen widget | Move the state into a small stateful widget around the toggle |
| A child needs to change its parent's data | The child holds the data itself | Pass a callback down, as in `FavoriteButton` |
| Passing the same value through five widgets | State is far from where it is used | Consider `InheritedWidget` or a state-management package |
The rule is to put state in the lowest widget that is an ancestor of every widget that reads or changes it. Data goes down through constructor arguments and events go up through callbacks.
Mistake 9: missing keys in reordered lists
When a list of stateful children is reordered, Flutter matches old and new children by type and position unless you give keys. The State objects stay in their positions while the widgets above them swap, so a checkbox's checked state appears to stick to the wrong item.
Give each stateful child a ValueKey built from a stable id, as in the TodoList example:
TodoTile(key: ValueKey(todo.id), todo: todo)Use an id that belongs to the item, not its index. An index key changes meaning when the list is reordered, so it fixes nothing. Do not use UniqueKey() or a random value in build. It creates a new key on every rebuild, so Flutter throws the State away each time.
Where mistakes happen in the lifecycle
Read the diagram as a map. Create objects on the arrow into Mounted, and release them on the arrow into Disposed. Refresh copied values while mounted, and check mounted before you touch the State from asynchronous code.
A quick review checklist
Before you commit a stateful widget, check these points:
- Every field change that affects the UI happens inside
setState. buildcreates no controllers and calls nosetState.- Every object created in
initStateis disposed indispose. - Every
awaitis followed by amountedcheck beforesetStateorcontextuse. - Values copied from
widgetare refreshed indidUpdateWidget, or read directly instead. - Derived values are getters, not stored fields.
- Stateful children in reorderable lists have
ValueKeys from stable ids.
Exercise
A screen shows a list of TodoTile widgets, each with its own checkbox state. After the user sorts the list, the checked boxes stay in the same rows while the titles move. There is no key on the tiles. What is the cause, and what is the fix?
Show answer
Without keys, Flutter matches old and new children by type and position, so each State (holding the checkbox value) stays at its row while the widget data moves. Give each tile key: ValueKey(todo.id), using a stable id from the item and not the list index, so each State follows its item.
Exercise
This code throws "setState() called after dispose()" when the user leaves the screen quickly. Fix it. Future<void> save() async { await api.save(data); setState(() => _saved = true); }
Show answer
Check mounted after the await and before setState:
Future<void> save() async {
await api.save(data);
if (!mounted) return;
setState(() => _saved = true);
}
The request can finish after the State is disposed, and mounted is false at that point.
Exercise
A widget stores _total as a field and updates it each time an item is added. A bug report says the total is sometimes wrong after items are removed. What is the design problem, and what is the better design?
Show answer
The total is derived data stored as a second source of truth, so every code path that changes the list must also remember to update _total. Remove the field and compute the total from the list with a getter such as double get _total => _items.fold(0.0, (s, p) => s + p);.