Lesson 0004 • Riverpod AsyncNotifier

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:

  1. Async / I/O state (useQuery / TanStack Query): Manages loading spinners, error states, and async resolution ({ data, isLoading, error }).
  2. 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&lt;CatalogSnapshot&gt;)"]
  Build --> State["state: AsyncValue&lt;CatalogSnapshot&gt;<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))"]
Figure 4.1: How Riverpod's catalogPersistenceProvider and Catalog AsyncNotifier wire persistence to ConsumerWidgets and headless tests.

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:

Domain exceptions and @Riverpod catalogPersistenceProvider in lib/catalog/catalog_provider.dart
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();
}

Block 2: Catalog AsyncNotifier, upsertPart, and (Container, Slot) Enforcement

Catalog AsyncNotifier build() and upsertPart() with 1-to-1 slot conflict checking
@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:

Block 3: Container Management, Cascading Unassignment & Quantity Clamping

Container CRUD with cascading part unassignment and clamped stock adjustments
  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));
  }

Block 4: Normalization & All-or-Nothing JSON Import Validation

LCSC normalization (Cxxxxxx), part field cleanup, and _commit
  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);
  }

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):

Upgrading WorkbenchScreen to ConsumerWidget in lib/main.dart
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(),
        },
      ),
    );
  }
}

3. Interactive Practice & Verification

Interactive Lab: Wiring Riverpod AsyncNotifier & ConsumerWidget

Skill Practice • Tight Feedback Loop

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."

:::

Retrieval Practice: Riverpod AsyncNotifier, Immutability & Store Seams

3 Questions • Equal-Length Options
1. How does a Riverpod AsyncNotifier like class Catalog extends _$Catalog compare to React state management?
2. What happens inside Catalog.deleteContainer(String containerId) when a user deletes a Container that holds parts?
3. Why does Catalog._commit(CatalogSnapshot next) update state = AsyncData(stamped) only after await persistence.save(stamped) completes?

Verification Lab: Run the Riverpod Catalog Store Test Suite

CLI Gate • Zero Warnings & 100% Green

Run static analysis and the test suite in tutorial/apps/0004-reactive-catalog-state-with-riverpod:

Terminal verification commands for Lesson 0004
cd tutorial/apps/0004-reactive-catalog-state-with-riverpod
flutter analyze
flutter test

Expected terminal output:

Verified output of flutter analyze && flutter test
Analyzing 0004-reactive-catalog-state-with-riverpod...
No issues found!
00:01 +8: All tests passed!