Flutter State Management
State is any value that can change after the widget is built: a counter, the text in a field, the items in a list, whether a panel is open. Flutter’s job is to rebuild the right part of the tree when that value changes, and the whole difficulty of “state management” is deciding where the value should live and how far a change should propagate. setState is enough for a single widget; once two widgets far apart in the tree need to agree on a value, you need a mechanism that carries it between them.
setState marks the element dirty, and on the next frame Flutter rebuilds that widget’s subtree.
class _SearchFieldState extends State<SearchField> {
String _query = '';
void _onChanged(String value) {
setState(() {
_query = value;
});
}
@override
Widget build(BuildContext context) {
return TextField(onChanged: _onChanged);
}
}
setState is the right tool when:
- the value is owned by exactly one widget, and
- only that widget’s own subtree cares about it.
Two rules matter. First, setState must be called from a State object, never during build. Second, mutate the field inside the callback you pass to setState, not before it - the callback is where the mutation is supposed to happen.
When two sibling widgets need the same value, the standard Flutter answer is to move the value to their common parent and pass it down.
class Parent extends StatefulWidget {
const Parent({super.key});
@override
State<Parent> createState() => _ParentState();
}
class _ParentState extends State<Parent> {
bool _expanded = false;
@override
Widget build(BuildContext context) {
return Column(
children: [
Header(onTap: () => setState(() => _expanded = !_expanded)),
if (_expanded) const Body(),
],
);
}
}
Lifting state up is simple and idiomatic, and it should be your first choice. The problem starts when the state needs to be shared by widgets in different branches, or when it is deep and passed through many intermediate widgets that do not care about it. That is when a dedicated state management solution pays for itself.
InheritedWidget lets a widget publish a value to its subtree. Widgets below can read it with context.dependOnInheritedWidgetOfExactType, and Flutter rebuilds those dependents when the value changes.
class ThemeScope extends InheritedWidget {
const ThemeScope({super.key, required this.accent, required super.child});
final Color accent;
static ThemeScope of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<ThemeScope>()!;
@override
bool updateShouldNotify(ThemeScope oldWidget) => accent != oldWidget.accent;
}
updateShouldNotify is the important part: return true only when the published value actually changed, otherwise every dependent is rebuilt for nothing.
Theme and MediaQuery are built on exactly this mechanism, which is why Theme.of(context) does not require you to pass anything down.
provider is the most widely used third-party solution. It turns state into a value that is published to the subtree, and it removes the need to thread state through constructor parameters.
class CounterNotifier extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => CounterNotifier(),
child: const MyApp(),
),
);
}
Reading the value in a widget:
class CounterText extends StatelessWidget {
const CounterText({super.key});
@override
Widget build(BuildContext context) {
final count = context.watch<CounterNotifier>().count;
return Text('$count');
}
}
context.watch<T>()subscribes the widget and rebuilds it whenTnotifies.context.read<T>()reads the value once, without subscribing - use it in callbacks.context.select<T>((t) => t.count)subscribes only to the part you select, so the widget rebuilds only when that specific value changes.
Provider also supports FutureProvider and StreamProvider for asynchronous data, and MultiProvider for several notifiers at once.
Riverpod is a compile-time-safe evolution of the same idea. Instead of looking state up from the widget tree, you declare providers that are resolved from a container.
final counterProvider =
StateNotifierProvider<CounterNotifier, int>((ref) => 0);
class CounterText extends ConsumerWidget {
const CounterText({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Text('$count');
}
}
The advantages over Provider are worth knowing: dependencies between providers are declared explicitly, providers can be overridden in tests without touching the widget tree, and because the lookup is static, a typo in a provider name is a compile error rather than a runtime failure. The cost is one more concept to learn and a slightly less standard API.
| Situation | Approach |
|---|---|
| One widget owns the value | setState |
| A parent and its children share the value | Lift state up |
| A theme or a value for a whole subtree | InheritedWidget |
| Many unrelated widgets share app-wide state | Provider |
| The same, with testability and compile-time safety | Riverpod |
| Server state that arrives asynchronously | FutureProvider / StreamProvider / Bloc |
A workable order of escalation is: start with setState, lift state up when siblings need it, and reach for Provider or Riverpod only when the shared state genuinely spans the app. Reaching for the biggest tool first is how apps end up with state management that is harder to follow than the problem it solves.
Approach: The question is about rebuild scope, so reason from what each mechanism subscribes to. setState rebuilds exactly one subtree, InheritedWidget rebuilds its dependents, and Provider’s watch rebuilds the watching widget whenever the notifier notifies - while select narrows that to a single derived value.
Steps:
setStateon a widget rebuilds that widget’s ownbuildmethod and the subtree below it. Siblings and parents are untouched.InheritedWidgetrebuilds the dependents that calleddependOnInheritedWidgetOfExactType, and only those, and only whenupdateShouldNotifyreturnstrue.context.watch<T>()subscribes the calling widget to every notification fromT, so the widget rebuilds on eachnotifyListeners()even if the value it actually uses has not changed.context.select<T>((t) => t.count)narrows the subscription to the selected value, so the widget rebuilds only whencountchanges - which is the cheaper option when the notifier also carries unrelated fields.
Answer: setState rebuilds one subtree, InheritedWidget rebuilds its dependents when the published value changes, watch rebuilds on every notification, and select rebuilds only when the selected value changes - so use select whenever the widget depends on just one part of a larger notifier.
With state under control, the remaining pages cover the parts of Flutter that separate a demo from a product: animations, custom painting, and the native integration that lets a Flutter app reach the platform it runs on.
