State Management
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
State is any data that can change while the app runs and that the UI depends on: the search text, the list of trails
loaded from the API, the set of favourite trails. Flutter rebuilds widgets when state changes, but it does not prescribe how
state is stored or shared; the community has produced several approaches with different trade-offs. This page walks from the
simplest to the most scalable and implements the Trailhead favourites feature with Riverpod
(flutter_riverpod 3.5.0). Widgets themselves are covered in Widgets and
Layout, and the data sources that feed the state in Data, Storage and Networking.
Ephemeral State and App State
| Ephemeral (local) state | App (shared) state | |
|---|---|---|
Scope |
One widget or one screen |
Several screens or the whole app |
Examples |
Current tab, text in a field, animation progress, a checkbox in a form |
Favourites, the signed-in user, the cached trail list, settings |
Where it lives |
A |
Outside the widget tree’s build methods, provided to many widgets |
Tool |
|
|
Start with ephemeral state and promote it to app state only when a second part of the UI needs the same data. Many problems attributed to "state management" come from lifting state higher than necessary.
setState
setState marks the widget dirty so that build runs again with the new values.
class FavouriteButton extends StatefulWidget {
const FavouriteButton({super.key});
@override
State<FavouriteButton> createState() => _FavouriteButtonState();
}
class _FavouriteButtonState extends State<FavouriteButton> {
bool _favourite = false;
@override
Widget build(BuildContext context) => IconButton(
icon: Icon(_favourite ? Icons.favorite : Icons.favorite_border),
onPressed: () => setState(() => _favourite = !_favourite),
);
}
This is correct for a toggle that no other screen cares about. It stops scaling when the same data must be shown in the list, the detail screen and a favourites tab, because passing values and callbacks through many constructors ("prop drilling") becomes unmanageable.
InheritedWidget
InheritedWidget is the framework primitive underneath Provider, Theme, MediaQuery and Riverpod’s scope. It exposes data to
all descendants, which look it up with context.dependOnInheritedWidgetOfExactType and rebuild when updateShouldNotify returns
true. Writing one by hand is rarely necessary, but the mechanism explains why Theme.of(context) triggers rebuilds.
class FavouritesScope extends InheritedWidget {
const FavouritesScope({super.key, required this.ids, required super.child});
final Set<String> ids;
static FavouritesScope of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<FavouritesScope>()!;
@override
bool updateShouldNotify(FavouritesScope old) => old.ids != ids;
}
ValueNotifier, ChangeNotifier and ListenableBuilder
The Listenable family in the framework is a built-in, dependency-free option. A ValueNotifier<T> holds one value and
notifies listeners when it is reassigned; a ChangeNotifier is a class that calls notifyListeners() after mutating its
fields. ListenableBuilder (and ValueListenableBuilder) rebuild only their subtree.
class FavouritesModel extends ChangeNotifier {
final Set<String> _ids = {};
Set<String> get ids => Set.unmodifiable(_ids);
void toggle(String id) {
_ids.contains(id) ? _ids.remove(id) : _ids.add(id);
notifyListeners();
}
}
// In a State: final model = FavouritesModel(); dispose it in dispose().
ListenableBuilder(
listenable: model,
builder: (context, _) => Text('${model.ids.length} favourites'),
)
The model must be created once (for example in initState) and disposed. Sharing it with distant widgets means passing it
down or wrapping it in an InheritedNotifier, which is what Provider automates.
Provider
provider 6.1.5+1 wraps InheritedWidget and lifecycle management in a small API: ChangeNotifierProvider creates and disposes
a ChangeNotifier, context.watch<T>() rebuilds on change, context.read<T>() reads without listening (use it in event
handlers) and context.select rebuilds only when a selected value changes.
void main() => runApp(
ChangeNotifierProvider(create: (_) => FavouritesModel(), child: const TrailheadApp()),
);
// In a widget:
final count = context.select<FavouritesModel, int>((m) => m.ids.length);
onPressed: () => context.read<FavouritesModel>().toggle(trail.id);
Provider is simple and widely used, and the Flutter documentation introduces it first. Its limits are that providers depend on
the widget tree (context is required to read them), asynchronous loading and error states are manual, and it is easy to
forget which ProviderNotFoundException scope is missing.
Riverpod 3
Riverpod (flutter_riverpod 3.5.0, by the author of Provider) declares state as global, compile-safe providers that do not
depend on BuildContext, supports asynchronous state natively with AsyncValue, and is easy to test with overrides. Wrap the
app in ProviderScope, and read providers through a ref:
| API | Purpose |
|---|---|
|
A read-only, computed or injected value (a repository, a derived list). |
|
Synchronous mutable state with methods that change it. |
|
State loaded asynchronously, exposed as |
|
Read and rebuild when the provider changes (use in |
|
Read once, without listening (use in callbacks). |
|
Run a side effect, such as a snackbar, when a provider changes. |
|
Widgets that receive a |
In Riverpod 3 the legacy StateNotifierProvider and StateProvider live in a separate legacy import; new code uses Notifier
and AsyncNotifier, and all providers retry failed loading automatically unless configured otherwise. Code generation with
riverpod_generator is optional and not used here.
Trailhead Favourites with Riverpod
The trail list loads asynchronously, so it is an AsyncNotifier. Favourites are a synchronous set, so they are a Notifier. A
TrailRepository (see Data, Storage and Networking) is injected through a plain Provider.
import 'package:flutter_riverpod/flutter_riverpod.dart';
final trailRepositoryProvider = Provider<TrailRepository>((ref) {
return TrailRepository(baseUrl: 'https://api.example.com/v1');
});
class TrailsNotifier extends AsyncNotifier<List<Trail>> {
@override
Future<List<Trail>> build() => ref.watch(trailRepositoryProvider).fetchTrails();
Future<void> refresh() async {
state = const AsyncLoading();
state = await AsyncValue.guard(() => ref.read(trailRepositoryProvider).fetchTrails());
}
}
final trailsProvider = AsyncNotifierProvider<TrailsNotifier, List<Trail>>(TrailsNotifier.new);
class FavouritesNotifier extends Notifier<Set<String>> {
@override
Set<String> build() => {};
void toggle(String id) {
state = state.contains(id) ? ({...state}..remove(id)) : {...state, id};
}
}
final favouritesProvider = NotifierProvider<FavouritesNotifier, Set<String>>(FavouritesNotifier.new);
/// Derived state: favourite trails, recomputed only when an input changes.
final favouriteTrailsProvider = Provider<List<Trail>>((ref) {
final ids = ref.watch(favouritesProvider);
final trails = ref.watch(trailsProvider).value ?? const <Trail>[];
return trails.where((t) => ids.contains(t.id)).toList();
});
State is always replaced with a new immutable value ({...state, id}), never mutated in place, because Riverpod 3 compares the
old and new state with == to decide whether to notify, and a collection mutated in place is still the same object, so it compares equal to itself. The UI consumes the providers:
class TrailsScreen extends ConsumerWidget {
const TrailsScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final trails = ref.watch(trailsProvider);
final favourites = ref.watch(favouritesProvider);
return Scaffold(
appBar: AppBar(title: const Text('Trailhead')),
body: switch (trails) {
AsyncData(:final value) => RefreshIndicator(
onRefresh: () => ref.read(trailsProvider.notifier).refresh(),
child: ListView.builder(
itemCount: value.length,
itemBuilder: (context, i) {
final trail = value[i];
return ListTile(
title: Text(trail.name),
trailing: IconButton(
icon: Icon(favourites.contains(trail.id) ? Icons.favorite : Icons.favorite_border),
onPressed: () => ref.read(favouritesProvider.notifier).toggle(trail.id),
),
);
},
),
),
AsyncError(:final error) => Center(child: Text('Could not load trails: $error')),
_ => const Center(child: CircularProgressIndicator()),
},
);
}
}
void main() => runApp(const ProviderScope(child: TrailheadApp()));
Persisting favourites across restarts is a storage concern; see Data, Storage and
Networking for shared_preferences or a database. Testing with provider overrides is shown in
Testing.
Unidirectional Data Flow
Every approach above works best when data flows one way: the UI reads state, user input becomes an event or method call, the state holder updates the state (often after calling a repository), and the UI is rebuilt from the new state.
The UI never changes state directly, and widgets contain no business rules; the state holder is a plain Dart class that can be tested without Flutter.
Comparing the Approaches
| Aspect | setState and ValueNotifier | Provider | Riverpod 3 | flutter_bloc 9.1.1 |
|---|---|---|---|---|
Boilerplate |
Lowest |
Low |
Low to medium |
Medium (events or methods, states) |
Needs |
Yes (passed down) |
Yes |
No (uses |
Yes ( |
Async and error state |
Manual |
Manual |
Built in ( |
Explicit states per case |
Compile-time safety |
Medium |
Runtime lookup errors possible |
High |
Medium |
Testability |
Good for notifiers |
Good |
Excellent (overrides, no widgets needed) |
Excellent ( |
Scalability |
Small apps |
Small to medium |
Small to large |
Medium to large, strict structure |
Learning curve |
Gentle |
Gentle |
Moderate |
Moderate to steep |
The same thinking applies in other ecosystems; compare the state-holder approaches in
React Native and the ViewModel pattern in
Kotlin Multiplatform.
Bloc and Cubit in Brief
flutter_bloc 9.1.1 provides Cubit (methods emit states) and Bloc (events are mapped to states). A Cubit for favourites:
class FavouritesCubit extends Cubit<Set<String>> {
FavouritesCubit() : super(const {});
void toggle(String id) =>
emit(state.contains(id) ? ({...state}..remove(id)) : {...state, id});
}
// BlocProvider(create: (_) => FavouritesCubit(), child: ...)
// BlocBuilder<FavouritesCubit, Set<String>>(builder: (context, ids) => Text('${ids.length}'))
Bloc shines in large teams that want a strict event-to-state contract and exhaustive state classes (a natural fit for the sealed classes in Dart Language Essentials).
Choosing an Approach
-
Use
setStatefor state owned by one widget, such as form inputs and animation controllers. -
Use
ValueNotifierorChangeNotifierwithListenableBuilderfor a small app or a single shared model. -
Use Riverpod for new applications with asynchronous data, caching, dependency injection and a need to test without a widget tree; it is the approach used for the rest of this section.
-
Use Provider if the team already uses it or the app is small and Provider-based tutorials fit.
-
Use Bloc or Cubit when the team prefers an explicit event-driven architecture or already standardized on it.
-
Whatever you choose, keep state immutable, keep business logic out of widgets, put side effects in the state holder, and keep one source of truth for each piece of data.
Routing can also hold state (the current location and its parameters); see Navigation and Routing.