implementing-riverpod
Skill7 starsChanged 8 months agoMITView on GitHub
Implements Riverpod (v3.3.x) compile-safe state management for Flutter apps. Use when implementing @riverpod code generation providers, handling AsyncValue loading/error/data states, using ref.watch/ref.read/ref.listen, setting up ProviderScope, writing Notifier/AsyncNotifier classes, using FutureProvider/StreamProvider, applying autoDispose and family modifiers, combining providers, testing providers in isolation, scoping rebuilds with Consumer instead of ConsumerWidget, using ref.watch with select() for field-level precision, migrating from StateNotifierProvider or Riverpod 2.x patterns, handling Notifier resource lifecycle with ref.onDispose, or using experimental Mutation and offline persistence APIs.
In this repository41 other files it gives its agents.
- .github/copilot-instructions.mdCopilot instructions
- skill-creatorSkill
- flutter-dbSkill
- flutter-routingSkill
- flutter-state-managementSkill
- configuring-codemagicSkill
- applying-effective-dartSkill
- deploying-with-fastlaneSkill
- integrating-firebaseSkill
- implementing-fl-chartSkill
- integrating-google-adsSkill
- animating-flutter-widgetsSkill
- routing-with-autorouteSkill
- implementing-flutter-blocSkill
- configuring-deep-linksSkill
- persisting-data-with-driftSkill
- building-flutter-production-appsSkill
- generating-flutter-uiSkill
- routing-with-gorouterSkill
- managing-hive-storageSkill
- using-flutter-hooksSkill
- running-flutter-isolatesSkill
- managing-flutter-provider-stateSkill
- implementing-responsive-layoutsSkill
- managing-secure-storageSkill
- flutter-setupSkill
- managing-shared-preferencesSkill
- implementing-flutter-social-authSkill
- flutter-testingSkill
- using-fpdartSkill
- generating-freezed-modelsSkill
- configuring-github-actionsSkill
- building-jaspr-web-appsSkill
- testing-with-marionetteSkill
- implementing-openapi-in-dartSkill
- integrating-revenuecatSkill
- integrating-sentrySkill
- developing-serverpod-backendSkill
- building-shadcn-flutter-uiSkill
- integrating-supabaseSkill
- converting-ts-to-dartSkill
The file
We split this skill into the rules it gives an agent
10 rules. About 0 are common, 0 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 121
Use ConsumerWidget only when the entire widget tree depends on provider state:
- Very specific: line 140
Use ref.watch(provider.select((s) => s.field)) to rebuild only when a specific field changes:
- Very specific: line 152
Use HookConsumerWidget when combining with flutter_hooks.
- Very specific: line 197
Compile-time safety: Use @riverpod code generation.
- Very specific: line 198
Immutable state: Keep state immutable; use Freezed for complex models.
- Very specific: line 200
Ref lifecycle: Never store ref in a variable or pass it outside provider scope.
- Very specific: line 201
AsyncValue.guard: Always wrap async state mutations in AsyncValue.guard().
- Very specific: line 202
⚠️ ref.mounted: Always check ref.mounted after await before updating state.
- Very specific: line 204
⚠️ ref.read in callbacks: Use ref.read in event handlers.
- Very specific: line 206
Scoped rebuilds: Prefer Consumer over ConsumerWidget.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Riverpod State Management (v3.3.x)
Goal
Implement compile-time safe, context-free state management using Riverpod. Use @riverpod code generation for all new code — the generator handles auto-dispose, family, and type safety automatically.
Process
Phase 1: Install Dependencies
Code Generation (Recommended):
dependencies:
flutter_riverpod: ^3.3.1
riverpod_annotation: ^4.0.2
dev_dependencies:
build_runner: ^2.14.1
riverpod_generator: ^4.0.3
riverpod_lint: ^3.1.3Manual only (no code generation):
dependencies:
flutter_riverpod: ^3.3.1Phase 2: Setup ProviderScope
void main() {
runApp(ProviderScope(child: MyApp()));
}Phase 3: Create Providers
Notifier (synchronous mutable state):
part 'counter.g.dart';
@riverpod
class Counter extends _$Counter {
@override
int build() => 0;
void increment() => state++;
void decrement() => state--;
}
// Generated: counterProviderAsyncNotifier (async mutable state):
@riverpod
class TodoList extends _$TodoList {
@override
Future<List<Todo>> build() async => fetchTodos();
Future<void> addTodo(String title) async {
state = const AsyncValue.loading();
state = await AsyncValue.guard(() async {
final todo = await apiClient.createTodo(title);
return [...await future, todo];
});
}
}
// Generated: todoListProviderFutureProvider with auto-retry:
@Riverpod(retry: myRetryStrategy)
Future<User> userProfile(Ref ref, String userId) async {
return fetchUser(userId);
}
Duration? myRetryStrategy(int retryCount, Object error) {
if (retryCount >= 5) return null;
return Duration(milliseconds: 200 * (1 << retryCount));
}→ See riverpod.md for manual providers, testing, Mutations, and offline persistence.
Phase 4: Consume Providers
Prefer Consumer to scope rebuilds to the smallest subtree. ConsumerWidget rebuilds the entire widget on every state change; Consumer rebuilds only its builder.
// Preferred: only Text rebuilds when count changes
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Consumer(
builder: (context, ref, _) {
final count = ref.watch(counterProvider);
return Text('Count: $count');
},
),
floatingActionButton: FloatingActionButton(
// ref.read in callbacks — never ref.watch
onPressed: () => ProviderScope.containerOf(context)
.read(counterProvider.notifier)
.increment(),
child: const Icon(Icons.add),
),
);
}
}Use ConsumerWidget only when the entire widget tree depends on provider state:
class CounterPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Scaffold(
appBar: AppBar(title: Text('Count: $count')),
body: CounterBody(count: count),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).increment(),
child: const Icon(Icons.add),
),
);
}
}Use ref.watch(provider.select((s) => s.field)) to rebuild only when a specific field changes:
Consumer(
builder: (context, ref, _) {
// Only rebuilds when isLoggedIn changes, ignoring other User fields
final isLoggedIn = ref.watch(authProvider.select((u) => u.isLoggedIn));
return isLoggedIn ? const HomeView() : const LoginView();
},
)Use HookConsumerWidget when combining with flutter_hooks. Use ref.listen for side-effects (snackbars, navigation) without triggering rebuilds.
→ See riverpod.md for detailed Consumer vs ConsumerWidget decision table and select() patterns.
Phase 5: Handle Async States
Widget build(BuildContext context, WidgetRef ref) {
final userAsync = ref.watch(userProfileProvider('u1'));
return userAsync.when(
data: (user) => Text('Hello, ${user.name}'),
loading: () => const CircularProgressIndicator(),
error: (e, st) => Text('Error: $e'),
);
}→ See PITFALLS.md for AsyncValue best practices and optimistic UI with copyWithPrevious.
Phase 6: Provider Dependencies
@riverpod
Future<List<Post>> userPosts(Ref ref, String userId) async {
final user = await ref.watch(userProfileProvider(userId).future);
return fetchPostsForUser(user.id);
}→ See PITFALLS.md for ref.mounted checks, memory leak prevention, and ref.read vs ref.watch rules.
Reference Documentation
- Riverpod Patterns (v3.x) — Code generation, manual providers, testing, experimental Mutations and persistence
- Common Pitfalls —
ref.mounted, memory leaks,ref.readvsref.watch, AsyncValue patterns - State Management Overview — ChangeNotifier/Provider decision guide
Constraints
- No BuildContext in providers: Access state via
refonly. - Compile-time safety: Use
@riverpodcode generation; catches errors at build time. - Immutable state: Keep state immutable; use Freezed for complex models. v3.0 uses
==for all state comparisons — implementoperator ==or use Freezed. - Auto-dispose by default: Code-gen providers auto-dispose unless marked
keepAlive: true. - Ref lifecycle: Never store
refin a variable or pass it outside provider scope. - AsyncValue.guard: Always wrap async state mutations in
AsyncValue.guard(). - ⚠️ ref.mounted: Always check
ref.mountedafterawaitbefore updating state. - ⚠️ ref.onDispose: Cancel timers, streams, and HTTP requests in
ref.onDispose. - ⚠️ ref.read in callbacks: Use
ref.readin event handlers;ref.watchonly inbuild(). - ⚠️ Notifier resource leak (v3.0): Notifier creates fresh instances on every rebuild — never store timers or controllers directly inside a Notifier. Extract to a dedicated
Providerwithref.onDispose. - Scoped rebuilds: Prefer
ConsumeroverConsumerWidget; useselect()for field-level precision.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

