/flutter:state-management-riverpodfrom Flutter Skills
Enforces Riverpod 3.x state management patterns: one Notifier/AsyncNotifier/StreamNotifier ViewModel per feature, immutable state with value equality, single write path through a repository, and unidirectional data flow. Covers provider DI, ref.watch/read/listen/select patterns, async modeling, and bans legacy providers.
Ships in Flutter Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
State and dependency injection are one mechanism: Riverpod 3.x. Each feature has one Notifier/AsyncNotifier/StreamNotifier ViewModel that exposes an immutable state value; dumb ConsumerWidgets read it. Widgets hold only ephemeral UI state; every durable mutation routes through one repository (the single write path). This skill covers the state-agnostic core first, then the Riverpod "how", then a Provider/ChangeNotifier appendix for the official Flutter-guide stack.
Read the reference for the task at hand:
references/ownership-and-lifecycle.md — the ownership table (which provider shape), family/autoDispose/onDispose rules, composition-root DI.references/reads-and-side-effects.md — watch vs read vs listen vs select, the stale-closure hole, void action methods, ref.mounted/BuildContext guards.references/riverpod3-api-and-testing.md — Riverpod 3.x API shifts (legacy moves, overrideWithValue, retry, ProviderContainer.test), what 2023 tutorials get wrong, and testing seams.Run scripts/ban-legacy-providers.sh before a PR.
These hold regardless of the state library.
freezed/sealed + copyWith), never a mutable field bag. Cross-feature/shared state lives in a repository, not a ViewModel — two ViewModels owning the same fact is two facts that will disagree.notifier.rename(id, name); it never sets state. This is the one door through which state changes, so every change is reviewable in one place.copyWith into a new instance.news a live collaborator and never holds a BuildContext. This is what makes it testable with fakes and swappable per flavor.AsyncValue (or a status enum + data + error) rendered exhaustively — never scattered isLoading/hasError booleans that can encode a half-set, impossible state.DateTime.now() in state logic. "Now" enters through an injected Clock (from package:clock) exposed as clockProvider, so time-dependent behaviour is deterministic in tests (clockProvider.overrideWithValue(Clock.fixed(t))). Never DateTime.now(), never a bespoke ClockService. service-boundary-and-native owns the clockProvider seam.Match the provider shape to what it owns (full table in references/ownership-and-lifecycle.md):
| Owns | Shape |
|---|---|
| Per-feature presentation state over a live query | StreamNotifier whose build() returns the repository stream |
| Per-feature presentation state, non-stream | Notifier / AsyncNotifier over one immutable value |
| A reactive projection of the DB | StreamProvider over a repository/DAO stream (never stored) |
An injected collaborator (repo, service, Clock) | plain Provider (DI) |
| Per-entity/per-session state | Notifier/AsyncNotifier/StreamNotifier .family + .autoDispose |
Default to hand-written providers (StreamNotifierProvider/AsyncNotifierProvider(...), .autoDispose/.family modifiers). @riverpod codegen is an optional convenience, not the default (see the reference). Riverpod 3.0 API only — base classes Notifier/AsyncNotifier/StreamNotifier; autoDispose/family are provider modifiers, never AutoDispose*/*Family base classes (removed in 3.0).
// features/task — one StreamNotifier ViewModel: build() returns the LIVE repo stream,
// so a committed write re-emits and the UI updates with no manual republish (D6).
class TaskListNotifier extends StreamNotifier<TaskListState> {
@override
Stream<TaskListState> build() {
final filter = ref.watch(taskFilterProvider); // in-session filter, its own Notifier
return ref.watch(taskRepositoryProvider).watchAll() // the live source of truth
.map((tasks) => TaskListState(tasks: tasks, filter: filter));
}
// Durable act routes through the single write path. void so the call site never drops
// the Future; no `state = ...` — the committed write makes watchAll() re-emit.
void complete(TaskId id) =>
unawaited(ref.read(taskRepositoryProvider).markComplete(id).catchError(_report));
void _report(Object error, StackTrace stack) {/* surface via a logger — never swallow */}
}
final taskListNotifierProvider =
StreamNotifierProvider.autoDispose<TaskListNotifier, TaskListState>(
TaskListNotifier.new);
// The reversible in-session filter is its own tiny Notifier (manual NotifierProvider).
class TaskFilterNotifier extends Notifier<TaskFilter> {
@override
TaskFilter build() => TaskFilter.all;
void set(TaskFilter f) => state = f; // watched by build() above; re-projects the stream
}
final taskFilterProvider =
NotifierProvider<TaskFilterNotifier, TaskFilter>(TaskFilterNotifier.new);
A ViewModel reads collaborators from providers; the composition root wires the live impls once. A placeholder seam throws until overridden, so an un-wired dependency fails loudly at first read instead of silently constructing a real service inside a test.
// A seam: throws until a flavor main() overrides it. One live impl per flavor.
final databaseProvider = Provider<AppDatabase>(
(ref) => throw UnimplementedError('override databaseProvider in main()'),
);
final taskRepositoryProvider = Provider<TaskRepository>(
(ref) => TaskRepository(ref.watch(databaseProvider)), // inject, never `new` a live DB here
);
// main.dart — the ONLY place live collaborators are constructed.
void main() {
final db = AppDatabase.open();
runApp(ProviderScope(
overrides: [databaseProvider.overrideWithValue(db)],
child: const App(),
));
}
Before adding a provider, ask whether a constructor argument would do. Provider count going up is a smell, not progress — reach for family/scoping/codegen only when a plain provider genuinely cannot express the need.
Full rationale in references/reads-and-side-effects.md.
ref.watch(p) / ref.watch(p.select((s) => s.field)) — in build(), for display. .select narrows the rebuild to one field. Never watch a whole controller at the top of a large widget.ref.read(p.notifier) — in callbacks (onTap, onPressed). A read of a value in build() freezes on stale data; a watch in a callback rebuilds unexpectedly.ref.listen(p, ...) — in build(), for side effects (navigate, snackbar) on change. Never fire a side effect directly from build().class TaskCounter extends ConsumerWidget {
const TaskCounter({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final n = ref.watch(taskListNotifierProvider.select((s) => s.value?.openCount ?? 0));
return Text('$n');
}
}
The stale-closure hole: never capture a ref.watched value into an onTap closure — pass a stable key and resolve at tap time via ref.read. A captured value silently acts on the previous entity after a fast re-tap, and no lint catches it.
// WRONG — acts on a stale item after a re-render.
onTap: () => ref.read(p.notifier).complete(task),
// RIGHT — id is stable; resolve now.
onTap: () => ref.read(p.notifier).complete(task.id),
Action-path methods return void. An arrow closure onTap: () => notifier.doThing() that "returns" a Future satisfies neither discarded_futures nor unawaited_futures (target type is VoidCallback), so the Future and its error are dropped. A void intent method makes the hole unreachable; kick off async inside it with unawaited(_run().catchError(_report)). See async-safety.
.family-keyed by a stable equatable value (an id or a @freezed args record), never a mutable object, and .autoDispose so heavy session state dies on unmount.Provider — never autoDispose.await with ref.mounted (the Riverpod analogue of use_build_context_synchronously).ref.onDispose (streams, controllers, native handles). Riverpod owns a StreamProvider's subscription, so don't hand-manage it.Read MediaQuery.boldTextOf(context) / .textScalerOf(context) / .highContrastOf(context) at build time in the widget, never via a provider. MediaQuery is already an InheritedWidget with correct-by-construction invalidation; routing it through a provider means either a BuildContext in a provider body or a one-frame-stale hand-sync. App/domain state via Riverpod; platform/a11y state via BuildContext. See accessibility-as-code.
StateProvider / StateNotifierProvider / ChangeNotifierProvider (moved to flutter_riverpod/legacy.dart), or adding get_it / package:provider / Bloc alongside Riverpod. Two DI/state mechanisms is strictly worse than one.ref.watch at the top of a big widget rebuilding the whole subtree on any field change. Use .select or a leaf ConsumerWidget.setState(). setState/local State is for ephemeral UI only (a toggle, an in-flight animation flag).news its collaborators, holds a BuildContext, navigates, or shows snackbars. Inject; publish state; let the view (or a router redirect) react.family-keying on a mutable object, or autoDispose on an app-scope singleton, or keepAlive() to undo an autoDispose you shouldn't have added.Notifier/AsyncNotifier/StreamNotifier over an immutable value; widgets hold only ephemeral UI state.AsyncValue/status rendered exhaustively; no loose loading/error booleans.ref.watch/.select for display, ref.read(p.notifier) in callbacks, ref.listen for side effects; no broad top-level watch; no captured-value closures.main; no BuildContext/DateTime.now() in the ViewModel.family-keyed by a stable value and autoDisposed; app singletons are plain providers; resources released in ref.onDispose.legacy.dart, get_it, package:provider, or Bloc import (scripts/ban-legacy-providers.sh passes).flutter-architecture — where ViewModels, repositories, and the write path sit in the feature-first DAG.error-handling-typed-results — the Result/Failure spine a repository method returns instead of throwing.async-safety — the Future-drop hole, mounted guards, subscription/timer disposal.persistence-drift — the Drift streams the StreamProviders project and the one-transaction-per-mutation write path.service-boundary-and-native — the throwing-seam provider pattern for every side effect and native channel; owns the clockProvider (package:clock) seam these ViewModels read instead of DateTime.now().widget-composition — the dumb ConsumerWidget Views that read this state.accessibility-as-code — the split this skill co-owns: app/domain state via Riverpod, platform/a11y state read from MediaQuery/BuildContext, never a provider.value-objects-money-and-units — value types that take a Clock param for deterministic time.app-startup-and-bootstrap — the composition root where ProviderScope overrides are wired.For the official Flutter-guide stack (package:provider + ChangeNotifier), the same ten rules hold; only the mechanism changes.
ChangeNotifier; new state = notifyListeners() after all fields are set (exactly once per logical change, never mid-update or in a loop)._private; expose read-only getters; return List.unmodifiable(...) — never hand out a mutable collection.Provider/ProxyProvider above the screen (auto-disposed on pop). Do not use get_it as the container.context.select/Consumer/Selector for display, context.read in callbacks. Read in didChangeDependencies or callbacks, never initState._disposed flag before notifyListeners() after an await; cancel subscriptions and dispose owned controllers in dispose().enum ViewStatus { idle, loading, ready, error }
class TaskListViewModel extends ChangeNotifier {
TaskListViewModel(this._repo); // injected abstraction
final TaskRepository _repo;
ViewStatus _status = ViewStatus.idle;
ViewStatus get status => _status;
List<Task> _tasks = const [];
List<Task> get tasks => List.unmodifiable(_tasks); // immutable view
int get openCount => _tasks.where((t) => !t.done).length; // derive, don't store
Future<void> load() async {
_status = ViewStatus.loading; notifyListeners();
try {
_tasks = await _repo.load();
_status = ViewStatus.ready;
} catch (_) {
_status = ViewStatus.error;
}
notifyListeners(); // exactly one, after all fields set
}
Future<void> complete(TaskId id) async {
await _repo.markComplete(id); // single write path
_tasks = [for (final t in _tasks) t.id == id ? t.copyWith(done: true) : t];
notifyListeners();
}
}
examples/composition_root.dart (opens in a new tab)examples/task_list_feature.dart (opens in a new tab)references/ownership-and-lifecycle.md (opens in a new tab)references/reads-and-side-effects.md (opens in a new tab)references/riverpod3-api-and-testing.md (opens in a new tab)scripts/ban-legacy-providers.sh (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub zakariaf/flutter-skills --plugin flutter40 skills in this plugin
/accessibility-as-codeEnforces accessibility as a correctness property authored into each widget — Semantics(button/label) or ExcludeSemantics on every node, a11y state read from MediaQuery not app state, never MediaQuery.withClampedTextScaling / textScaleFactor / FittedBox / TextOverflow.ellipsis to fit a label, non-color redundant channels (icon+label+shape+text) for every state, contrast against composited backgrounds (4.5:1 body / 3:1 large), 44px single-tap targets, OrdinalSortKey traversal, and honoring boldText / reduce-motion. Use when adding a GestureDetector/InkWell or any tap target, adding an Icon or Image, reaching for withClampedTextScaling/FittedBox/ellipsis/textScaleFactor to make text fit, encoding state via color, sizing type, ordering focus traversal, or reviewing any View for screen-reader/switch/low-vision support./adaptive-layoutEnforces adapting layout by available CONSTRAINTS/size, never device or platform checks — LayoutBuilder + MediaQuery.sizeOf/paddingOf/viewInsetsOf (not .of) for narrow rebuilds, Material 3 window size classes (compact <600, medium 600-840, expanded 840-1200, large >1200) as the breakpoint vocabulary, navigation affordance chosen by width (NavigationBar → NavigationRail → NavigationDrawer), list-detail single-pane-vs-two-pane, readable max-width via ConstrainedBox, Flexible/Expanded/FractionallySizedBox over fixed widths, SafeArea + display cutouts + keyboard insets, never lock orientation, foldable/hinge awareness via MediaQuery.displayFeatures, and golden-matrix verification across sizes. Use when building responsive or adaptive UI, tablet/desktop/foldable support, master-detail or two-pane screens, a NavigationRail-vs-BottomNav shell, breakpoints, LayoutBuilder, MediaQuery sizing, SafeArea/cutouts, or fixing overflow at large widths./ads-and-iap-monetizationEnforces opt-in, rewarded-first monetization over the service seam — a rewarded view grants exactly one benefit and only on a genuine reward outcome (a sealed Rewarded/Dismissed/NoFill), earn loops capped per day against an injected Clock, the earn control preloaded and hidden unless an ad is loaded so a fresh account never dead-ends on "no ads available" (a Guideline 2.1 risk), interstitials only at a natural break under a count-and-elapsed cap owned by the service so callers stay dumb, no banner on the primary work surface, one non-consumable unlock plus Restore re-checked each launch and committed through the single write path before the UI reacts, one derived isEntitled provider as the only gate, and the entitlement restored BEFORE the ad SDK initializes so a paying user never starts it, resolves consent, or sees a tracking prompt. Use when adding ads, wiring a rewarded earn loop, placing an interstitial, building a paywall, gating an entitlement, or setting up ad units./app-startup-and-bootstrapEnforces a fixed main() cold-launch order — crash-log sink + FlutterError.onError + PlatformDispatcher.onError installed BEFORE any code that can throw, settings/theme read before runApp so the first frame paints correct, real infra constructed in a composition-root bootstrap() and injected via ProviderScope overrideWithValue over throwing placeholder providers, non-blocking warm-up deferred to addPostFrameCallback, exactly two error handlers with NO runZonedGuarded, ProviderException unwrapped before logging, and a WidgetsBindingObserver that flushes durable state on background/resume. Use when editing lib/main.dart, main_<flavor>.dart, bootstrap.dart or app.dart, reordering anything in main(), adding a splash/onboarding/permission gate, restoring theme before first paint, wiring a DB or service into ProviderScope, handling app-lifecycle background/resume flushes, or chasing cold-start latency, ANRs, or first-frame jank./async-safetyEnforces no-silent-failure async discipline in Flutter/Dart — the arrow-callback Future-drop hole no lint catches (`onTap: () => vm.save(x)`), void-returning event handlers, a mounted/ref.mounted guard after EVERY await before touching BuildContext, capturing Navigator/ScaffoldMessenger before the gap, honest `unawaited()` that always ends in catchError, no empty/bare catches, `rethrow` over `throw e`, and disposing every StreamSubscription/StreamController/Timer/sink. Use when writing or reviewing async/await, wiring onTap/onPressed/onSubmitted or any VoidCallback, touching BuildContext after an await, writing initState/dispose/addPostFrameCallback, adding a Timer or Future.delayed, writing a try/catch, or seeing use_build_context_synchronously, cancel_subscriptions, close_sinks, unawaited_futures, or discarded_futures./ci-pipeline-and-gatesEnforces a lean GitHub Actions Flutter CI where every gate maps to one named release-blocking contract — pinned runner + subosito/flutter-action@v2 toolchain, dart format --set-exit-if-changed, flutter analyze --fatal-infos, build_runner and drift schema freshness (git diff --exit-code), flutter test --test-randomize-ordering-seed random, static import/banned-string greps that catch what runtime can't, coverage-as-report-never-a-gate with the upward-lie fixed, verify-never-bless goldens (no --update-goldens in CI), and an honest statement of what CI cannot prove (audio, real fonts, on-device behaviour). Use when editing .github/workflows/*.yml, adding or removing a job or step, wiring a codegen/schema/format/analyze/coverage gate, writing a grep-based policy test or gate script under test/policy or tool/, pinning action versions, or claiming CI proves something it can't.Other plugins' skills for the same job