Skip to main content
skill CX Codex

riverpod — Claude Code skill: what it does, how to install

This skill guides Riverpod work in Flutter and Dart, from provider setup to lifecycle handling and tests. Use it when an agent needs project-specific state-management guidance.

MIT ★ 674 updated 2026-10-29

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add evanca/flutter-ai-rules
/plugin install flutter-ai-skills@flutter-ai-rules
Open on GitHub

What riverpod does

The skill lays out patterns for defining providers, accessing them through ref, and passing arguments. It covers composing asynchronous providers, cleaning up resources with ref.onDispose, and triggering side effects from UI handlers. Widgets that consume providers should use ConsumerWidget or ConsumerStatefulWidget.

It also addresses disposal, eager initialization, and tests built with ProviderContainer or ProviderScope and dependency overrides. Parameterized providers should use autoDispose to avoid retaining state after listeners go away. The listed platforms are Claude Code and Codex.

What it helps with

  • define providers for a Flutter app
  • combine results from asynchronous providers
  • dispose provider state and resources
  • pass family arguments with suitable equality
  • test providers with fake dependencies

Example prompts for the agent

  • Set up Riverpod providers for this Flutter app and review their lifecycle.
  • Combine the asynchronous provider results and handle loading and error states.
  • Write a provider test with a fake repository and a separate ProviderContainer.

How to install riverpod

1Plugin marketplace

/plugin marketplace add evanca/flutter-ai-rules
/plugin install flutter-ai-skills@flutter-ai-rules

This installs the whole flutter-ai-skills plugin with all its skills

2Skills CLI (Vercel)

npx skills add evanca/flutter-ai-rules --skill riverpod -a claude-code

3Manually: put the files in place

~/.claude/skills/riverpod/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/riverpod/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about riverpod

How do I install riverpod in Claude Code?

Add the marketplace with /plugin marketplace add evanca/flutter-ai-rules, then install the skill with /plugin install flutter-ai-skills@flutter-ai-rules.

What does the riverpod skill do?

It guides Riverpod usage in Flutter and Dart, including provider setup, argument handling, state disposal, side effects, and testing.

How does the skill handle tests for autoDispose providers?

It recommends a fresh ProviderContainer or ProviderScope for each test. For autoDispose providers, use container.listen to keep the state alive during the test.

Source text

SKILL.md · MIT
---
name: riverpod
description: "Use when setting up providers, combining requests, managing state disposal, passing arguments, performing side effects, or testing providers (Riverpod)."
license: MIT
---

# Riverpod Skill

This skill defines how to correctly use Riverpod for state management in Flutter and Dart applications.

---

## 1. Setup

```dart
void main() {
  runApp(const ProviderScope(child: MyApp()));
}
```

- Wrap your app with `ProviderScope` directly in `runApp` — never inside `MyApp`.
- Install and use `riverpod_lint` to enable IDE refactoring and enforce best practices.

---

## 2. Defining Providers

```dart
// Functional provider (codegen)
@riverpod
int example(Ref ref) => 0;

// FutureProvider (codegen)
@riverpod
Future<List<Todo>> todos(Ref ref) async {
  return ref.watch(repositoryProvider).fetchTodos();
}

// Notifier (codegen)
@riverpod
class TodosNotifier extends _$TodosNotifier {
  @override
  Future<List<Todo>> build() async {
    return ref.watch(repositoryProvider).fetchTodos();
  }

  Future<void> addTodo(Todo todo) async { ... }
}
```

- Define all providers as **`final` top-level variables**.
- Use `Provider`, `FutureProvider`, or `StreamProvider` based on the return type.
- Use `ConsumerWidget` or `ConsumerStatefulWidget` instead of `StatelessWidget`/`StatefulWidget` when accessing providers.

---

## 3. Using Ref

| Method | Use for |
|---|---|
| `ref.watch` | Reactively listen — rebuilds when value changes. Use during build phase only. |
| `ref.read` | One-time access — use in callbacks/Notifier methods, not in build. |
| `ref.listen` | Imperative subscription — prefer `ref.watch` where possible. |
| `ref.onDispose` | Cleanup when provider state is destroyed. |

```dart
// In a widget
class MyWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final value = ref.watch(myProvider);
    return Text('$value');
  }
}

// Cleanup in a provider
final provider = StreamProvider<int>((ref) {
  final controller = StreamController<int>();
  ref.onDispose(controller.close);
  return controller.stream;
});
```

- **Never** call `ref.watch` inside callbacks, listeners, or Notifier methods.
- Use `ref.read(yourNotifierProvider.notifier).method()` to call Notifier methods from the UI.
- Check `context.mounted` before using `ref` after an `await` in async callbacks.

---

## 4. Combining Providers

```dart
@riverpod
Future<String> userGreeting(Ref ref) async {
  final user = await ref.watch(userProvider.future);
  return 'Hello, ${user.name}!';
}
```

- Use `ref.watch(asyncProvider.future)` to await an async provider's resolved value.
- Providers only execute once and cache the result — multiple widgets listening to the same provider share one computation.

---

## 5. Passing Arguments (Families)

```dart
@riverpod
Future<Todo> todo(Ref ref, String id) async {
  return ref.watch(repositoryProvider).fetchTodo(id);
}

// Usage
final todo = ref.watch(todoProvider('some-id'));
```

- Always enable `autoDispose` for parameterized providers to prevent memory leaks.
- Use `Dart 3 records` or code generation for multiple parameters — they naturally override `==`.
- Avoid passing plain `List` or `Map` as parameters (no `==` override); use `const` collections, records, or classes with proper equality.
- Use the `provider_parameters` lint rule from `riverpod_lint` to catch equality mistakes.

---

## 6. Auto Dispose & State Lifecycle

- With codegen: state is **destroyed by default** when no longer listened to. Opt out with `keepAlive: true`.
- Without codegen: state is **kept alive by default**. Use `.autoDispose` to enable disposal.
- State is always destroyed when a provider is recomputed.

```dart
// keepAlive with timer
ref.onCancel(() {
  final link = ref.keepAlive();
  Timer(const Duration(minutes: 5), link.close);
});
```

- Use `ref.onDispose` for cleanup; do not trigger side effects or modify providers inside it.
- Use `ref.invalidate(provider)` to force destruction; use `ref.invalidateSelf()` from within the provider.
- Use `ref.refresh(provider)` to invalidate and immediately read the new value — always use the return value.

---

## 7. Eager Initialization

Providers are **lazy** by default. To eagerly initialize:

```dart
// In MyApp or a dedicated widget under ProviderScope:
Consumer(
  builder: (context, ref, _) {
    ref.watch(myEagerProvider); // forces initialization
    return const MyApp();
  },
)
```

- Place eager initialization in a public widget (not `main()`) for consistent test behavior.
- Use `AsyncValue.requireValue` to read data directly and throw clearly if not ready.

---

## 8. Performing Side Effects

```dart
@riverpod
class TodosNotifier extends _$TodosNotifier {
  Future<void> addTodo(Todo todo) async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(() async {
      await ref.read(repositoryProvider).addTodo(todo);
      return [...?state.value, todo];
    });
  }
}

// In UI:
ElevatedButton(
  onPressed: () => ref.read(todosNotifierProvider.notifier).addTodo(todo),
  child: const Text('Add'),
)
```

- Use `ref.read` (not `ref.watch`) in event handlers.
- After a side effect, update state by: setting it directly, calling `ref.invalidateSelf()`, or manually updating the cache.
- Always handle loading and error states in the UI.
- Do not perform side effects in provider constructors or build methods.

---

## 9. Provider Observers

```dart
class MyObserver extends ProviderObserver {
  @override
  void didUpdateProvider(ProviderObserverContext context, Object? previousValue, Object? newValue) {
    print('[${context.provider}] updated: $previousValue → $newValue');
  }

  @override
  void providerDidFail(ProviderObserverContext context, Object error, StackTrace stackTrace) {
    // Report to error service
  }
}

runApp(ProviderScope(observers: [MyObserver()], child: MyApp()));
```

---

## 10. Testing

```dart
// Unit test
final container = ProviderContainer(
  overrides: [repositoryProvider.overrideWith((_) => FakeRepository())],
);
addTearDown(container.dispose);

expect(await container.read(todosProvider.future), isNotEmpty);

// Widget test
await tester.pumpWidget(
  ProviderScope(
    overrides: [repositoryProvider.overrideWith((_) => FakeRepository())],
    child: const MyApp(),
  ),
);
```

- Create a **new** `ProviderContainer` or `ProviderScope` for each test — never share state between tests.
- Use `container.listen` over `container.read` for `autoDispose` providers to keep state alive during the test.
- Use `overrides` to inject mocks or fakes.
- Prefer mocking **dependencies** (repositories) rather than Notifiers directly.
- If you must mock a Notifier, **subclass** the original — don't use `implements` or `with Mock`.
- Place Notifier mocks in the same file as the Notifier if using code generation.
- Obtain the container in widget tests with `ProviderScope.containerOf(tester.element(...))`.

---

## References

- [Riverpod GitHub Repository](https://github.com/rrousselGit/riverpod)

© Ivanna Kaceviča · MIT · evanca/flutter-ai-rules

Similar skills

All skills for Mobile →

From the same set39

The whole set →
revenuecat-testing revenuecat-testing builds a structured QA plan for RevenueCat in-app subscriptions, verifies sandbox events, and debugs purchase restore flows. CX Codex +1 ★ 674repo stars firebase-app-check This skill guides Firebase App Check setup in Flutter, including provider choice, debug tokens, token refresh, and enforcement rollout. CX Codex +1 ★ 674repo stars flutter-best-practices flutter-best-practices is a Claude Code skill with rules for Flutter and Dart: layers, feature folders, widget choices, and tests. The agent reads the reference file matching the task. CX Codex +1 ★ 674repo stars flutter-app-architecture flutter-app-architecture enforces layered Flutter architecture with MVVM, repositories, services, and unidirectional data flow. CX Codex +1 ★ 674repo stars architecture-feature-first architecture-feature-first sets up a layered, feature-first structure for Flutter apps, splitting UI, data and an optional domain layer. CX Codex +1 ★ 674repo stars inclusive-design inclusive-design guides agent workflows on low-end hardware, metered 2G connections, global name formats, and novice stress. Distinct from WCAG audits. CX Codex +1 ★ 674repo stars firebase-database The firebase-database skill guides Flutter work with Firebase Realtime Database, from JSON structure and queries to live updates, offline support, and access rules. CX Codex +1 ★ 674repo stars dart-3-updates dart-3-updates — a skill for Claude Code and Codex that teaches the AI to write switch expressions, patterns, records, and modern Dart instead of old if-else chains. Helps when refactoring to Dart 3 and choosing between records and classes. CX Codex +1 ★ 674repo stars

Project sponsors

Companies that keep this analytics open