Sub topic 8
Choosing between stateless and stateful
This chapter assumes you can write a basic StatelessWidget and StatefulWidget, and that you know what setState does and how a State object survives rebuilds. It does not cover the full State lifecycle, keys, or lifting state up in detail. Those have their own chapters. This one covers how to decide which kind of widget to write, and how to fix the choice when you get it wrong.
The deciding question
Every widget in Flutter is immutable. A widget object is a configuration, and Flutter creates a new one whenever the parent rebuilds. The real question is therefore not "does my UI change?" Almost every UI changes. The question is:
Who owns the data that changes, and does this widget need to remember it between rebuilds?
- If the data arrives through the constructor, the parent owns it. The widget can be stateless.
- If the data is created and changed inside this widget, and must survive rebuilds, the widget owns it. It needs a
Stateobject.
A stateless widget can show different things over time. It does this because its parent passes in new arguments, not because it changes itself.
What counts as state
State is data that meets all three conditions:
- It can change while the widget is on screen.
- A change must update the UI.
- It cannot be recomputed from the widget's constructor arguments.
The third condition is the one people forget. A value you can compute from widget.price or from an InheritedWidget is not state. It is derived data, and it belongs in a local variable inside build.
import 'package:flutter/material.dart';
class PriceTag extends StatelessWidget {
const PriceTag({super.key, required this.cents, required this.quantity});
final int cents;
final int quantity;
@override
Widget build(BuildContext context) {
final total = (cents * quantity) / 100;
return Text('\$${total.toStringAsFixed(2)}');
}
}total changes whenever the parent passes a new quantity, yet PriceTag needs no state. Storing total in a State field would add a second source of truth that you would have to keep in sync.
A decision flow
Work through these questions in order. Stop at the first one that applies.
The last branch matters. If a value is only needed during one build call, compute it there and keep the widget stateless.
Situations that call for a StatefulWidget
Local UI state that only this widget cares about
Examples are whether a tile is expanded, which tab is selected, or whether a password is visible. No other widget reads these values, so a parent would gain nothing from owning them.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: ExpandableNote()))));
class ExpandableNote extends StatefulWidget {
const ExpandableNote({super.key});
@override
State<ExpandableNote> createState() => _ExpandableNoteState();
}
class _ExpandableNoteState extends State<ExpandableNote> {
bool _expanded = false;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
TextButton(
onPressed: () => setState(() => _expanded = !_expanded),
child: Text(_expanded ? 'Hide details' : 'Show details'),
),
if (_expanded) const Text('These are the details.'),
],
);
}
}_expanded is created here, changed here, and cannot be derived from anything the parent passes in. That makes it ephemeral state, which suits a StatefulWidget.
Objects with a lifecycle
Controllers, focus nodes, animation controllers, stream subscriptions, and timers must be created once and released later. A stateless widget has no place to do either. Its build method can run many times per second, so creating a TextEditingController there would leak a new controller on every rebuild and discard the user's typed text each time.
If your widget holds anything that has a dispose() or cancel() method, it almost certainly needs a State class.
Values that must persist across rebuilds
Scroll offsets, a half-typed form value, and the current frame of an animation all live in objects that must outlive any single widget instance. State objects are kept by Flutter while the widget stays in the same place in the tree, so they are the right home for them.
Situations that stay stateless
| Situation | Why stateless is enough |
|---|---|
| Displays values passed by the parent | The parent owns the data |
| Formats or combines its inputs | Derived data belongs in `build` |
| Reports user actions through a callback | The parent decides what to do with the event |
| Reads theme or media data via `BuildContext` | Inherited data triggers rebuilds without local state |
| A reusable layout wrapper | It has no data of its own |
Callbacks are the main reason this list is long. A button that triggers onToggle does not need to know what is being toggled. Keeping such widgets stateless makes them easy to test, since the same inputs always produce the same output.
The most common wrong choice: copying a property into state
A frequent mistake is making a widget stateful so that it can "own a copy" of a constructor argument:
import 'package:flutter/material.dart';
class StaleLabel extends StatefulWidget {
const StaleLabel({super.key, required this.name});
final String name;
@override
State<StaleLabel> createState() => _StaleLabelState();
}
class _StaleLabelState extends State<StaleLabel> {
late String _name;
@override
void initState() {
super.initState();
_name = widget.name; // copied once, never updated
}
@override
Widget build(BuildContext context) {
return Text(_name);
}
}When the parent rebuilds with a different name, Flutter keeps the existing State and only swaps the widget property. initState does not run again, so _name stays at the old value and the screen shows stale text. The fix is to read widget.name directly in build:
import 'package:flutter/material.dart';
class FreshLabel extends StatelessWidget {
const FreshLabel({super.key, required this.name});
final String name;
@override
Widget build(BuildContext context) {
return Text(name);
}
}There is one legitimate version of the copy. Sometimes a constructor argument is only an initial value, such as initialName in a text field, and the user edits it afterward. In that case the field is real state, and the name should say so: initialName, not name. If you also need to react when the parent supplies a different initial value, that is the job of didUpdateWidget, covered in the lifecycle chapter.
Trade-offs at a glance
| Concern | StatelessWidget | StatefulWidget |
|---|---|---|
| Amount of code | Less | More: two classes |
| Testing | Pass arguments, check output | Must also drive interactions and the lifecycle |
| Reuse | High, since behavior depends only on inputs | Lower, since hidden state can surprise callers |
| `const` construction | Easy | Possible for the widget, but its `State` still rebuilds |
| Risk of leaks | None from the widget itself | Forgetting `dispose` leaks resources |
| Where bugs hide | In the parent that supplies data | In `setState` timing and lifecycle code |
Neither kind is faster in general. A stateless widget costs nothing extra to rebuild, and a stateful widget only costs more if setState is called high in the tree, so that large subtrees rebuild. The performance chapter covers how to limit that.
Changing your mind later
The choice is not permanent, and the refactoring is mechanical. Two moves cover most cases:
- Stateful to stateless. If you find that nothing in the
Stateclass is truly owned, delete the fields and read fromwidgetor from a parent. - Stateless to stateful. If you add a controller or a local toggle, convert the class. Android Studio and VS Code offer a "Convert to StatefulWidget" quick action that creates the
Stateclass for you.
When a second widget starts needing the same value, move the field up to the nearest common parent, as in the FavoriteScreen and FavoriteButton pair you saw earlier. The child becomes stateless and receives isFavorite and onToggle. Moving state up usually reduces the number of stateful widgets in an app.
A short checklist
Before writing extends StatefulWidget, confirm that at least one of these is true:
- You need
setStatefor a value that no constructor argument supplies. - You create an object that must be disposed or cancelled.
- You need to run code once when the widget enters the tree, or when it leaves.
- You must remember something across rebuilds that cannot be recomputed.
If none applies, write a StatelessWidget.
Exercise
A ProductRow widget receives name, unitCents, and quantity from its parent and shows "Widget x3 — $7.50". A teammate proposes a StatefulWidget that stores _total in initState to avoid recomputing it. Which kind of widget should ProductRow be, and what goes wrong with the teammate's design when the parent changes quantity?
Show answer
ProductRow should be a StatelessWidget that computes the total inside build. In the teammate's design, initState runs only once, when the State is created. When the parent passes a new quantity, Flutter keeps the existing State and only replaces its widget, so _total is never recalculated and the row shows a stale price. The total is derived data, so it should not be stored as state.
Exercise
You are building a search box that creates a TextEditingController, and a results list that needs the current query text. Which widgets should be stateful, and where should the controller be created and released?
Show answer
The search box should be a StatefulWidget. Create the controller in initState and call dispose on it in dispose, because it is an object with a lifecycle. If the results list needs the query, either have the search box report changes through an onChanged callback, or lift the query to a common parent and pass it down. The results list can then stay stateless.