flutter-state-management
State management in Flutter apps: detecting the installed approach and following it — Riverpod 2/3 (Notifier/AsyncNotifier, code-gen @riverpod, ref.watch/read/listen, overrides), Bloc/Cubit (events, s
Files1
View on GitHubSKILL.mdplugins/flutter-plugin/skills/flutter-state-management/SKILL.md
GitHubFlutter State Management
Rule zero: use what is installed
| Signal in pubspec.yaml | Approach |
|---|---|
flutter_riverpod / hooks_riverpod |
Riverpod; riverpod_annotation + riverpod_generator → code-gen @riverpod style |
flutter_bloc / bloc |
Bloc or Cubit — mirror which one neighbouring features use |
provider (without Riverpod/Bloc) |
ChangeNotifier + ChangeNotifierProvider |
get |
GetX controllers — follow existing patterns, do not expand GetX's service-locator use |
mobx + flutter_mobx |
Stores with @observable/@action + code-gen |
| none | ValueNotifier / ChangeNotifier + ListenableBuilder, constructor-injected repositories |
Never add a second library. If the BA spec seems to need one, list it in BLOCKERS.
Layering (all approaches)
Widget ──watches──▶ Notifier / Bloc / Controller ──calls──▶ Repository (interface) ──▶ API client / DB / platform
- Widgets render state and forward user intents. No
await api.…in widgets. - Notifiers/blocs hold presentation logic and call repositories. They do not import
package:flutter/material.dart(exceptfoundation.dartforChangeNotifier), never take aBuildContext. - Repositories map DTOs to domain models and translate transport errors into domain failures.
Modelling async state
Every async screen has four states: loading, empty, error, data. Make the type force you to handle them.
Riverpod gives you AsyncValue<T>:
final orders = ref.watch(ordersProvider);
return switch (orders) {
AsyncData(:final value) when value.isEmpty => const OrdersEmpty(),
AsyncData(:final value) => OrdersList(orders: value),
AsyncError(:final error) => ErrorView(error: error, onRetry: () => ref.invalidate(ordersProvider)),
_ => const Center(child: CircularProgressIndicator.adaptive()),
};
Elsewhere, a sealed state:
sealed class OrdersState { const OrdersState(); }
final class OrdersLoading extends OrdersState { const OrdersLoading(); }
final class OrdersLoaded extends OrdersState { const OrdersLoaded(this.orders); final List<Order> orders; }
final class OrdersFailure extends OrdersState { const OrdersFailure(this.message); final String message; }
If the project uses a single state class with a status enum (common in Bloc codebases with copyWith), follow that instead.
Riverpod
- Code-gen style when
riverpod_annotationis present:
@riverpod
Future<List<Order>> orders(Ref ref) async {
final repo = ref.watch(orderRepositoryProvider);
return repo.fetchOrders();
}
@riverpod
class Cart extends _$Cart {
@override
List<CartItem> build() => const [];
void add(CartItem item) => state = [...state, item];
}
- Without code-gen:
NotifierProvider/AsyncNotifierProvider(Riverpod 2+). Do not write newStateNotifierProvider/ChangeNotifierProvidercode in a Riverpod 2+ project — they are legacy. ref.watchinbuild(widgets and providers) to depend;ref.readinside callbacks (onPressed) to act;ref.listenfor side effects.- Narrow rebuilds with
ref.watch(provider.select((s) => s.total)). autoDispose(the code-gen default) for screen-scoped state;keepAlive: trueonly for genuinely app-wide state.- Family/parameterized providers for per-id data:
ref.watch(orderProvider(orderId)). - Mutations in an
AsyncNotifier: setstate = const AsyncLoading()thenstate = await AsyncValue.guard(() => repo.save(...)). - Dependencies are providers too — override them in tests and flavors (
ProviderScope(overrides: [...])). - Check the major version in
pubspec.lockbefore writing provider code:- Riverpod 3: one
Reftype (noFooRef, no generic);StateProvider/StateNotifierProvider/ChangeNotifierProviderlive inpackage:flutter_riverpod/legacy.dart;Overrideand similar helper types inmisc.dart. A failing provider is retried automatically — passretry: (count, error) => nullon the provider (or onProviderScope) where a failure must surface immediately, e.g. a 401 or a validation error. - Riverpod 2: code-gen functions take a generated
FooRef; there is no automatic retry.
- Riverpod 3: one
Bloc / Cubit
- Cubit for simple state with method calls; Bloc when events need transformation (debounce, droppable, restartable via
bloc_concurrency) or an audit trail. Match neighbours. - Events and states are immutable; states use
equatable/freezedor sealed classes soBlocBuilderskips identical emits. - Never emit after
close()— guard long operations withif (isClosed) return;. - Provide blocs with
BlocProvider(create: (_) => OrdersBloc(context.read<OrderRepository>())..add(const OrdersRequested()))at the route/screen level, not app-wide unless truly global. - UI:
BlocBuilder/BlocSelectorto rebuild;buildWhento narrow.BlocListenerfor one-off effects (snackbar, navigation);listenWhento narrow.BlocConsumerwhen both are needed.context.read<B>().add(...)in callbacks; nevercontext.watchinside callbacks.
- Persist only when the project already uses
hydrated_bloc.
Provider / ChangeNotifier
- Call
notifyListeners()once per logical change, after state is consistent. context.watch<T>()in build,context.read<T>()in callbacks,context.select<T, R>(...)to narrow.- Dispose owned resources in
dispose();ChangeNotifierProvider(create: ...)disposes for you,.valuedoes not.
Side effects (snackbars, dialogs, navigation)
Never trigger them from build. Use the listener primitive of the approach:
- Riverpod:
ref.listen(checkoutProvider, (prev, next) { if (next case AsyncError(:final error)) showError(context, error); });insidebuildof aConsumerWidget(listen is allowed there; it does not run the effect during build). - Bloc:
BlocListener. - ChangeNotifier:
addListenerininitState, removed indispose.
Dependency injection
- Riverpod: repositories and clients are providers.
- Bloc/Provider:
RepositoryProvider/Providerat the app root, orget_it(+injectable) if the project already registers services there. - Never instantiate a repository or
Dioinside a widget.
Forms
- Field values live in
TextEditingControllers (widget state) or in the notifier when validation depends on several fields — follow the project. - Validate on submit and on field change after first submit; show errors via
InputDecoration.errorTextorTextFormField.validator. - Disable the submit button while a submission is in flight; show progress inside it.