Sub topic 1
Why setState is not enough: ephemeral state vs app state
Every Flutter app keeps data that changes over time. Some of that data belongs to one widget and can be thrown away when the widget disappears. Other data is shared across screens, survives navigation, or comes from a server. setState handles the first kind well and handles the second kind poorly. This chapter explains where that boundary lies and what a state management library has to provide once you cross it.
Prerequisites
This chapter assumes you already know:
- Dart basics: classes, generics,
async/awaitand null safety. - Flutter widget fundamentals:
StatelessWidget,StatefulWidget,BuildContextandsetState. - What a Dart
Streamis. You do not need to have used one heavily.
You do not need to know the bloc package yet. The chapter ends with a first look at it, and later chapters cover it in detail.
Two kinds of state
Flutter's own documentation separates state into two categories.
- Ephemeral state (also called local or UI state) is state that one widget can own completely. No other part of the app needs it, and losing it on restart is acceptable.
- App state is state that several widgets or screens read or change, that must survive when a widget leaves the tree, or that the user would be upset to lose.
| Question | Ephemeral state | App state |
|---|---|---|
| Who reads it? | One widget | Many widgets or screens |
| Lifetime | Same as the widget | Longer than any one widget |
| Typical examples | Selected tab, text field focus, animation progress, "is this tile expanded" | Logged-in user, cart contents, fetched list, theme, settings |
| Good home | `StatefulWidget` and `setState` | An object outside the widget tree |
There is no hard line. A selected tab index is ephemeral until a deep link needs to open a specific tab. At that point another part of the app needs to set it, and it has become app state.
Where setState works well
Here is a tile that expands and collapses. Nothing else in the app cares whether it is open.
import 'package:flutter/material.dart';
class ExpandableTile extends StatefulWidget {
const ExpandableTile({super.key, required this.title, required this.body});
final String title;
final String body;
@override
State<ExpandableTile> createState() => _ExpandableTileState();
}
class _ExpandableTileState extends State<ExpandableTile> {
bool _expanded = false;
@override
Widget build(BuildContext context) {
return Column(
children: [
ListTile(
title: Text(widget.title),
trailing: Icon(_expanded ? Icons.expand_less : Icons.expand_more),
onTap: () => setState(() => _expanded = !_expanded),
),
if (_expanded)
Padding(
padding: const EdgeInsets.all(16),
child: Text(widget.body),
),
],
);
}
}This is the right tool. The state is one boolean, one widget owns it, and the rebuild is small. Adding a library here would only add code.
Where setState breaks down
Problems appear when state stops being local. The usual symptoms fall into five groups.
Sharing state forces you to lift it
If two sibling widgets need the same value, it has to move up to their nearest common ancestor. The ancestor then passes the value and a callback down through every constructor in between. This is often called prop drilling.
class ShopPage extends StatefulWidget {
const ShopPage({super.key});
@override
State<ShopPage> createState() => _ShopPageState();
}
class _ShopPageState extends State<ShopPage> {
int _cartCount = 0;
void _addToCart() => setState(() => _cartCount++);
@override
Widget build(BuildContext context) {
// Every widget between here and the button must accept and forward both.
return ProductList(cartCount: _cartCount, onAdd: _addToCart);
}
}
class ProductList extends StatelessWidget {
const ProductList({super.key, required this.cartCount, required this.onAdd});
final int cartCount;
final VoidCallback onAdd;
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Cart: $cartCount'),
ElevatedButton(onPressed: onAdd, child: const Text('Add')),
],
);
}
}With one level this is fine. With six levels, every intermediate widget carries parameters it does not use, and a new screen outside ShopPage cannot reach the cart at all.
Rebuilds are too broad
setState rebuilds the whole build method of the state's widget. When the state lives high in the tree to be shared, a small change such as a counter increment rebuilds a large subtree.
Business logic ends up inside widgets
Look at a screen that loads data with setState.
import 'package:flutter/material.dart';
Future<List<String>> fetchTodos() async {
await Future<void>.delayed(const Duration(seconds: 1));
return ['Write tests', 'Ship feature'];
}
class TodosScreen extends StatefulWidget {
const TodosScreen({super.key});
@override
State<TodosScreen> createState() => _TodosScreenState();
}
class _TodosScreenState extends State<TodosScreen> {
bool _loading = false;
String? _error;
List<String> _todos = [];
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
setState(() {
_loading = true;
_error = null;
});
try {
final todos = await fetchTodos();
if (!mounted) return;
setState(() {
_todos = todos;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = e.toString();
_loading = false;
});
}
}
@override
Widget build(BuildContext context) {
if (_loading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
if (_error != null) {
return Scaffold(body: Center(child: Text(_error!)));
}
return Scaffold(
body: ListView(
children: [for (final todo in _todos) ListTile(title: Text(todo))],
),
);
}
}This works, but several things are wrong with it as the app grows:
- The loading logic cannot be tested without pumping a widget, because it is tangled with the UI.
- The state is three separate fields. Nothing prevents
_loadingand_errorfrom both being set, which is a combination that should be impossible. - The
mountedchecks exist because the widget can be disposed while the request is in flight. Every async method needs them. - Leaving the screen throws the data away. Coming back repeats the request.
- Another screen that wants the same todos has to copy all of this.
State is invisible and hard to trace
When any method can call setState with any change, you cannot easily answer "what caused this state?" There is no single place that records the sequence of changes, so debugging means placing prints in many methods.
Lifetime is tied to the widget
A State object lives and dies with its widget. If a user flow needs a value to outlive a screen, or a background task to continue after the user navigates away, a widget is the wrong owner.
What a structure needs to provide
The problems above point to a short list of requirements for anything that holds app state:
- A home outside the widgets. The object holding state has its own lifetime and can be shared by looking it up, not by passing it through constructors.
- One immutable state value. The UI renders from a single object, so impossible combinations can be made unrepresentable.
- Controlled change. State changes go through named methods or events, so every change has a visible cause.
- Targeted rebuilds. Widgets subscribe to the part of the state they display.
- Testability. The logic runs in plain Dart tests with no widget tree.
The following diagram shows the data flow that the bloc library uses to meet these requirements.
The widget never changes the state directly. It asks the Cubit to do something, the Cubit produces a new state object, and the widget redraws from it. The direction of flow is always the same.
A first look at Cubit
A Cubit is the simplest object in the bloc library that meets those requirements. It holds one state value and exposes methods that replace it.
import 'package:flutter_bloc/flutter_bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}The class is plain Dart with no widget imports in its logic. A test can create it, call increment() and check the result. The next chapters build this up: first immutable state, then Cubits, then wiring them to the widget tree.
Deciding where state should live
Use these questions in order for any piece of state:
- Does only one widget read and write it? Use
setState. - Is it purely visual and safe to lose, such as scroll position, animation progress or focus? Keep it local even if it feels important.
- Do other widgets or screens need it, or must it outlive the widget? Move it into a Cubit or Bloc.
- Does it involve asynchronous work, such as network or storage, with loading and error outcomes? Move it into a Cubit or Bloc, even if only one screen uses it today.
Common mistakes
- Treating "uses a network" as the only test for app state. The better test is whether the state is shared or must outlive the widget.
- Lifting state far too high. Putting a value in the root widget so one distant child can read it makes the whole tree rebuild on each change.
- Calling
setStateafterdispose. This throws a framework error. Guard withmounted, or better, move the async work out of the widget. - Keeping parallel booleans for status.
isLoading,hasErrorandisDonecan disagree. A single status value cannot.
Exercise
A settings screen has a "dark mode" switch. The switch is shown on the settings screen, but the whole app theme must change when it is toggled, and the choice should still apply when the user opens a different screen. Is this ephemeral state or app state, and why is setState in the settings screen a poor fit?
Show answer
It is app state. Several parts of the app (the theme at the top of the tree and the settings screen) read it, and it must outlive the settings screen. A setState in the settings screen's State object would only rebuild that screen and would be lost when the screen is popped. The value needs an owner outside the widget, such as a Cubit provided above MaterialApp.
Exercise
In the TodosScreen example, name two problems that would remain even if you moved the loading logic into a separate helper function that is still called from the widget's State class.
Show answer
Any two of: the state is still three independent fields that can contradict each other (for example loading and error both set); the data is still lost when the screen leaves the tree and must be reloaded; other screens still cannot share the todos; the mounted checks are still required; and the logic is still hard to test without a widget because the results are written through setState.