Reactive Catalog State with Riverpod AsyncNotifier
Combine TanStack Query's async lifecycle and Zustand/Redux's immutable actions into a single @Riverpod AsyncNotifier (lib/catalog/catalog_provider.dart) and connect it to WorkbenchScreen via ConsumerWidget.
How Riverpod Unifies TanStack Query and Zustand/Redux
In a modern React application, you typically split state management across two different mental models:
- Async / I/O state (
useQuery/ TanStack Query): Manages loading spinners, error states, and async resolution ({ data, isLoading, error }). - Client store actions (Zustand / Redux Toolkit): Holds synchronous domain mutations (
upsertPart,adjustQuantity,deleteContainer).
In Flutter with Riverpod, AsyncNotifier unifies both! A class annotated with @Riverpod(keepAlive: true) defines an async build() method that loads initial state (returning a Future<CatalogSnapshot>), automatically wraps the state in a sealed AsyncValue<CatalogSnapshot> (AsyncLoading, AsyncData, AsyncError), and exposes typed mutation methods right on the notifier (ref.read(catalogProvider.notifier).adjustQuantity(...)).
flowchart LR Persist["catalogPersistenceProvider<br/>(FileCatalogPersistence or InMemory override)"] --> Build["Catalog.build()<br/>(Future<CatalogSnapshot>)"] Build --> State["state: AsyncValue<CatalogSnapshot><br/>(AsyncLoading | AsyncData | AsyncError)"] Mut["Mutations: upsertPart, adjustQuantity,<br/>deleteContainer, importSnapshot"] --> Commit["_commit(next)<br/>(await persistence.save → state = AsyncData)"] Commit --> State State --> UI["ConsumerWidget / ProviderContainer<br/>(ref.watch(catalogProvider))"]
1. Building lib/catalog/catalog_provider.dart Block by Block
Block 1: Domain Exceptions & catalogPersistenceProvider
First, we define typed domain exceptions for (Container, Slot) collisions and invalid JSON backups, plus the catalogPersistence provider seam:
import 'dart:convert';
import 'dart:math' as math;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'catalog_models.dart';
import 'catalog_persistence.dart';
import 'file_catalog_persistence.dart';
part 'catalog_provider.g.dart';
class SlotOccupiedException implements Exception {
const SlotOccupiedException({
required this.containerId,
required this.slot,
required this.occupyingPart,
});
final String containerId;
final String slot;
final Part occupyingPart;
@override
String toString() =>
'Slot "$slot" is already occupied by "${occupyingPart.name}".';
}
class CatalogImportValidationException implements Exception {
const CatalogImportValidationException(this.message);
final String message;
@override
String toString() => message;
}
@Riverpod(keepAlive: true)
CatalogPersistence catalogPersistence(Ref ref) {
return FileCatalogPersistence();
}@Riverpod(keepAlive: true):- By default,
@riverpodenablesautoDispose: if no widget is currently watching a provider, Riverpod disposes its state to free memory (similar to unmounting a component in React). - For our application-wide catalog store and persistence service,
keepAlive: truetells Riverpod to keep the cached catalog alive across screen and modal sheet transitions. riverpod_generatorreadsCatalogPersistence catalogPersistence(Ref ref)and generatescatalogPersistenceProviderinsidecatalog_provider.g.dart.
- By default,
Block 2: Catalog AsyncNotifier, upsertPart, and (Container, Slot) Enforcement
@Riverpod(keepAlive: true)
class Catalog extends _$Catalog {
@override
Future<CatalogSnapshot> build() async {
final persistence = ref.watch(catalogPersistenceProvider);
return persistence.load();
}
Future<void> upsertPart(Part part) async {
final current = await future;
final normalized = _normalizePart(part);
if (normalized.containerId != null &&
!current.containers.any((c) => c.id == normalized.containerId)) {
throw ArgumentError(
'Unknown containerId "${normalized.containerId}".',
);
}
final occupying = current.findOccupyingSlotPart(
normalized.containerId,
normalized.slot,
excludingPartId: normalized.id,
);
if (occupying != null) {
throw SlotOccupiedException(
containerId: normalized.containerId!,
slot: normalized.slot!,
occupyingPart: occupying,
);
}
final updatedParts = [...current.parts];
final existingIdx = updatedParts.indexWhere((p) => p.id == normalized.id);
if (existingIdx >= 0) {
updatedParts[existingIdx] = normalized;
} else {
updatedParts.add(normalized);
}
await _commit(current.copyWith(parts: updatedParts));
}Unpacking how AsyncNotifier works compared to React hooks:
class Catalog extends _$Catalog: Becausebuild()returnsFuture<CatalogSnapshot>,riverpod_generatormakes_$CataloganAsyncNotifier<CatalogSnapshot>and exportscatalogProvider.final current = await future;: Inside anAsyncNotifier, thefuturegetter awaits the completion ofbuild()(if it is still loading) and returns the unwrappedCatalogSnapshot.final updatedParts = [...current.parts];: Just like JavaScript array spread ([...current.parts]), Dart supports the spread operator...inside list, set, and map literals to shallow-clone a collection before mutating or appending!await _commit(current.copyWith(parts: updatedParts));: StampsupdatedAtin UTC, persists atomically viacatalogPersistenceProvider, and updatesstate = AsyncData(stamped).
Block 3: Container Management, Cascading Unassignment & Quantity Clamping
Future<void> upsertContainer(Container container) async {
final current = await future;
final name = container.name.trim();
if (name.isEmpty) {
throw ArgumentError('Container name is required.');
}
final normalized = container.copyWith(
name: name,
description: _nullIfEmpty(container.description),
);
final updatedContainers = [...current.containers];
final existingIdx =
updatedContainers.indexWhere((c) => c.id == normalized.id);
if (existingIdx >= 0) {
updatedContainers[existingIdx] = normalized;
} else {
updatedContainers.add(normalized);
}
await _commit(current.copyWith(containers: updatedContainers));
}
Future<void> deleteContainer(String containerId) async {
final current = await future;
final updatedContainers =
current.containers.where((c) => c.id != containerId).toList();
final updatedParts = current.parts.map((part) {
if (part.containerId == containerId) {
return part.copyWith(containerId: null, slot: null);
}
return part;
}).toList();
await _commit(
current.copyWith(
containers: updatedContainers,
parts: updatedParts,
),
);
}
Future<void> adjustQuantity(String partId, int delta) async {
await _updatePartQuantity(partId, (currentQty) => currentQty + delta);
}
Future<void> setQuantity(String partId, int exactQuantity) async {
await _updatePartQuantity(partId, (_) => exactQuantity);
}
Future<void> _updatePartQuantity(
String partId,
int Function(int currentQty) computeNext,
) async {
final current = await future;
final idx = current.parts.indexWhere((p) => p.id == partId);
if (idx < 0) return;
final part = current.parts[idx];
final nextQty = math.max(0, computeNext(part.quantity));
final updatedParts = [...current.parts];
updatedParts[idx] = part.copyWith(quantity: nextQty);
await _commit(current.copyWith(parts: updatedParts));
}- Lazy
Iterablevs.List(.where(...).toList()and.map(...).toList()):In JavaScript,array.filter(...)andarray.map(...)immediately allocate and return a newArray. In Dart,.where(...)and.map(...)return a lazyIterable<T>—you call.toList()at the end of the pipeline to materialize aList<T>. - Cascading container deletion: Deleting a Container never deletes your Parts; it atomically resets
containerId: null, slot: nullon any part stored in that container so those parts move safely back toUnassigned (Loose / Inbox). - Clamping at zero (
math.max(0, ...)): Whether you tap-10on a resistor withquantity: 5or callsetQuantity('p-1', -5),_updatePartQuantityclamps the resulting quantity to>= 0.
Block 4: Normalization & All-or-Nothing JSON Import Validation
static String? normalizeLcscCodeOrNull(String? raw) {
if (raw == null) return null;
final trimmed = raw.trim();
if (trimmed.isEmpty) return null;
final upper = trimmed.toUpperCase();
final withPrefix = upper.startsWith('C') ? upper : 'C$upper';
return RegExp(r'^C\d+$').hasMatch(withPrefix) ? withPrefix : null;
}
Future<void> _commit(CatalogSnapshot next) async {
final stamped = next.copyWith(updatedAt: DateTime.now().toUtc());
final persistence = ref.read(catalogPersistenceProvider);
await persistence.save(stamped);
state = AsyncData(stamped);
}normalizeLcscCodeOrNull: Accepts'14663','c14663', or' C14663 'and normalizes it to'C14663'(or returnsnullif it doesn't match^C\d+$).- All-or-nothing
validateCatalogJson(String rawJson): Parses and validates incoming JSON backups before touching live state—checkingschemaVersion == 1, ISO-8601updatedAt, unique container and part IDs, non-negative quantities, validcontainerIdreferences, and zero duplicate(containerId, slot)pairs. Notice how it uses a Dart 3 anonymous Record typefinal occupiedSlots = <String, ({String slot, String partName})>{};—equivalent to an inline TypeScript object type{ slot: string; partName: string }without needing to declare a class!
2. Connecting WorkbenchScreen via ConsumerWidget (lib/main.dart)
In React, a component subscribes to store state by calling a hook like const catalog = useSelector(...) or useQuery(...). In Flutter with Riverpod, you change extends StatelessWidget to extends ConsumerWidget, which adds WidgetRef ref as the second parameter to build(BuildContext context, WidgetRef ref):
class WorkbenchScreen extends ConsumerWidget {
const WorkbenchScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncCatalog = ref.watch(catalogProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Electronics Parts Tracker'),
),
body: Center(
child: switch (asyncCatalog) {
AsyncData(:final value) => Text(
'Workbench Ready — ${value.parts.length} parts cataloged',
),
AsyncError(:final error) => Text('Error loading catalog: $error'),
_ => const CircularProgressIndicator(),
},
),
);
}
}final asyncCatalog = ref.watch(catalogProvider);: Subscribes this widget'sElementtocatalogProvider. WheneverCatalogassigns a newstate = AsyncData(stamped), only widgets watchingcatalogProviderrebuild!- Dart 3
switchexpression with pattern destructuring:switch (asyncCatalog) { ... }is an expression that returns aWidgetdirectly (unlike JavaScript's statement-onlyswitch).AsyncData(:final value)destructures thevaluegetter (CatalogSnapshot) out ofAsyncData—equivalent toconst { value } = asyncCatalogin TypeScript!
3. Interactive Practice & Verification
Fill in the missing Riverpod and Dart 3 tokens below:
@Riverpod()
class Catalog extends _$Catalog {
@override
Future<CatalogSnapshot> build() async {
final persistence = ref.(catalogPersistenceProvider);
return persistence.load();
}
Future<void> _commit(CatalogSnapshot next) async {
final stamped = next.copyWith(updatedAt: DateTime.now().toUtc());
final persistence = ref.read(catalogPersistenceProvider);
await persistence.save(stamped);
state = ;
}
}
class WorkbenchScreen extends {
const WorkbenchScreen({super.key});
@override
Widget build(BuildContext context, ref) {
final asyncCatalog = ref.watch(catalogProvider);
// ...
}
}:::prompts hint: "Keep global providers alive with 'keepAlive: true', subscribe inside build() with 'ref.watch', wrap resolved state in 'AsyncData(stamped)', and use 'ConsumerWidget' with 'WidgetRef ref'." success: "Awesome! You've connected Riverpod's AsyncNotifier lifecycle to a reactive ConsumerWidget."
:::
AsyncNotifier like class Catalog extends _$Catalog compare to React state management?Catalog.deleteContainer(String containerId) when a user deletes a Container that holds parts?Catalog._commit(CatalogSnapshot next) update state = AsyncData(stamped) only after await persistence.save(stamped) completes?Run static analysis and the test suite in tutorial/apps/0004-reactive-catalog-state-with-riverpod:
cd tutorial/apps/0004-reactive-catalog-state-with-riverpod
flutter analyze
flutter testExpected terminal output:
Analyzing 0004-reactive-catalog-state-with-riverpod...
No issues found!
00:01 +8: All tests passed!