Sub topic 14
Common Mistakes with State
This chapter assumes basic Dart classes, constructors, final fields, named parameters, and null safety. You should also have a Flutter installation that can run a simple app.
State is data that can change while a widget is on screen. Flutter must know when that data changes so it can rebuild the affected widgets. Most state bugs happen when state is stored in the wrong place, changed without notifying Flutter, or used after its widget has been removed.
Changing state without setState
Changing a field does not automatically update the screen. The change must happen inside setState. The callback tells Flutter that this State object needs to build again.
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;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Text('Count: $_count'),
),
floatingActionButton: FloatingActionButton(
onPressed: _increment,
child: const Icon(Icons.add),
),
);
}
}Calling setState too often can waste work, but forgetting it causes a more direct problem: the field changes in memory while the old value remains visible.
Do not make asynchronous work itself the argument to setState. Change the state inside the callback instead.
Updating after disposal
An asynchronous operation can finish after the user leaves the page. At that point, the State object is unmounted. Calling setState can produce an error and may indicate that a resource or operation was not cleaned up.
flowchart TD
A[Start asynchronous work] --> B[Wait for result]
B --> C{State is mounted?}
C -->|Yes| D[Call setState]
C -->|No| E[Stop without updating UI]The mounted check prevents an update to a removed widget. It does not cancel the operation. For long-running work, cancellation is usually better than simply ignoring the result.
Putting initialization in build
Flutter may call build many times. Creating a controller, starting a request, or adding a listener in build can therefore happen repeatedly. This creates duplicate listeners, wasted requests, and memory leaks.
Create long-lived objects in initState and release them in dispose. If a widget property changes and the object must be updated, use didUpdateWidget.
| Object or action | Create or start | Release or stop |
|---|---|---|
| TextEditingController | initState | dispose |
| Timer | initState | dispose |
| Stream subscription | initState | dispose or cancel |
A controller created from widget.initialName also needs careful handling. That initial value is used when the State is first created. If the parent later supplies a different value, the controller does not change automatically. Decide whether the parent owns the text or whether the field owns it, then synchronize it deliberately.
Confusing widget properties with state
A StatefulWidget is immutable. Its fields describe the configuration supplied by the parent. Mutable values that belong to the widget's ongoing behavior belong in its State object.
For example, changing widget.title is impossible because title is final. Store a changing selection, loading flag, or counter in State. If the parent should control that value, keep it in the parent and pass it down with a callback.
Losing state in lists
Flutter matches old and new widgets by type and position unless keys provide a better identity. When list items are reordered, a text field or checkbox can keep the state of its previous position.
Give stateful list children a stable key based on an item identifier, such as ValueKey(todo.id). Do not use the list index when items can be inserted, removed, or reordered.
Choosing where state belongs
Keep state in the smallest widget that needs it. If two sibling widgets need the same value, move that value to their nearest common parent. The parent passes data down and receives events through callbacks.
This pattern prevents two copies of the same state from becoming inconsistent.
Exercise
A page starts a delayed request, the user navigates away, and the request finishes. What should the completion callback do before calling setState?
Show answer
It should check mounted and return if the State object is no longer mounted. Long-running work should also be cancelled when possible.