This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilehigh PriorityID: flutter-riverpod-v2

Flutter Riverpod 2.5+ Code Generation & AsyncValue Standard

Modern state management and dependency injection in Flutter using Riverpod 2.5+ code generation. Forbids legacy StateNotifierProvider; mandates @riverpod annotations, autoDispose lifecycle, and compile-safe AsyncValue.when() UI branching.

Prohibited Anti-Pattern: AI outputs legacy Riverpod 1.0 StateNotifierProvider boilerplate with manual state mutations and missing loading/error UI states.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Flutter Riverpod 2.5+ Code Generation & AsyncValue Standard - Modern state management and dependency injection in Flutter using Riverpod 2.5+ code generation. Forbids legacy StateNotifierProvider; mandates @riverpod annotations, autoDispose lifecycle, and compile-safe AsyncValue.when() UI branching.
globs: **/*provider*.dart, **/*controller*.dart, **/*state*.dart
alwaysApply: false
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/flutter-riverpod-v2"
---

# Flutter Riverpod 2.5+ Code Generation & AsyncValue Standard

> **Severity**: HIGH | **Category**: mobile
> **Anti-Pattern Warning**: AI outputs legacy Riverpod 1.0 StateNotifierProvider boilerplate with manual state mutations and missing loading/error UI states.

## System Constraints
You are a senior Flutter mobile architect. In Riverpod 2.5+, NEVER write legacy StateNotifierProvider or ChangeNotifierProvider boilerplate. Always use Riverpod code generation with the @riverpod annotation. Handle asynchronous data using AsyncValue.when() to guarantee exhaustive compile-time checking for loading, error, and data UI states.

## Strict Guidelines
- Use Riverpod code generation with `@riverpod` annotations; do NOT write legacy StateNotifierProvider or StateProvider classes.
- Handle async state exclusively with `AsyncValue.when(data: ..., loading: ..., error: ...)`; never leave error states unhandled.
- Leverage automatic disposal (`autoDispose` is default in code generation) to prevent memory leaks when screens pop off navigation.
- Pass parameters via family providers using functional syntax (`@riverpod Future<Product> product(ProductRef ref, String id)`).

## Bad vs Good Implementations
### Riverpod Code Generation & AsyncValue.when vs Verbose Legacy StateNotifier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: StateNotifierProvider requires verbose boilerplate, lacks type-safe family parameter code generation, and leaks state by default.
```dart
// ANTI-PATTERN: Obsolete Riverpod 1.0 StateNotifierProvider boilerplate
import 'package:flutter_riverpod/flutter_riverpod.dart';

// Verbose, boilerplate-heavy class requiring manual notifier wiring
class UserStateNotifier extends StateNotifier<AsyncValue<User>> {
  UserStateNotifier() : super(const AsyncValue.loading());

  Future<void> fetchUser(String id) async {
    try {
      final user = await api.getUser(id);
      state = AsyncValue.data(user);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }
}

final userProvider = StateNotifierProvider<UserStateNotifier, AsyncValue<User>>((ref) {
  return UserStateNotifier(); // Lacks automatic disposal!
});
```

#### Production Standard (Correct)
> **Standard**: The @riverpod generator produces type-safe providers, eliminates boilerplate, enables auto-disposal, and forces exhaustive UI branching.
```dart
// PRODUCTION STANDARD: Modern Riverpod 2.5+ Code Generation
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

part 'user_provider.g.dart';

@riverpod
Future<User> userProfile(UserProfileRef ref, {required String userId}) async {
  // Automatically disposed when no longer listened to
  final repository = ref.watch(userRepositoryProvider);
  return repository.fetchUser(userId);
}

// Consuming widget with exhaustive AsyncValue.when branching
class UserProfileScreen extends ConsumerWidget {
  final String userId;
  const UserProfileScreen({super.key, required this.userId});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final asyncUser = ref.watch(userProfileProvider(userId: userId));

    return Scaffold(
      body: asyncUser.when(
        data: (user) => Text('Welcome, ${user.name}'),
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (err, stack) => Center(child: Text('Failed: $err')),
      ),
    );
  }
}
```

### Invalidating Cache on User Action

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Bypasses Riverpod declarative dependency tree, leading to stale cache across multiple consumers.
```dart
// ANTI-PATTERN: Manually calling fetchUser inside widget state
onPressed: () => ref.read(userProvider.notifier).fetchUser("123")
```

#### Production Standard (Correct)
> **Standard**: Invalidates the provider, triggering automatic re-execution and propagating fresh data to all active screen subscribers.
```dart
// PRODUCTION STANDARD: Declarative Cache Invalidation via ref.invalidate
onPressed: () => ref.invalidate(userProfileProvider(userId: "123"))
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Flutter Riverpod 2.5+ Code Generation & AsyncValue Standard

Flutter Riverpod 2.5+ Code Generation & AsyncValue Standard defines an industrial-grade behavioral standard for mobile engineering. Modern state management and dependency injection in Flutter using Riverpod 2.5+ code generation. Forbids legacy StateNotifierProvider; mandates @riverpod annotations, autoDispose lifecycle, and compile-safe AsyncValue.when() UI branching. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI outputs legacy Riverpod 1.0 StateNotifierProvider boilerplate with manual state mutations and missing loading/error UI states. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI outputs legacy Riverpod 1.0 StateNotifierProvider boilerplate with manual state mutations and missing loading/error UI states.High
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Use Riverpod code generation with `@riverpod` annotations

Use Riverpod code generation with `@riverpod` annotations; do NOT write legacy StateNotifierProvider or StateProvider classes.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Handle async state exclusively with `AsyncValue.when(data

Handle async state exclusively with `AsyncValue.when(data: ..., loading: ..., error: ...)`; never leave error states unhandled.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Leverage automatic disposal (`autoDispose` is default in code generation) to prevent memory leaks when screens pop off navigation.

Leverage automatic disposal (`autoDispose` is default in code generation) to prevent memory leaks when screens pop off navigation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Pass parameters via family providers using functional syntax (`@riverpod Future<Product> product(ProductRef ref, String id)`).

Pass parameters via family providers using functional syntax (`@riverpod Future<Product> product(ProductRef ref, String id)`).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Flutter Riverpod 2.5+ Code Generation & AsyncValue Standard critical for AI coding assistants?

Modern state management and dependency injection in Flutter using Riverpod 2.5+ code generation. Forbids legacy StateNotifierProvider; mandates @riverpod annotations, autoDispose lifecycle, and compile-safe AsyncValue.when() UI branching. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI outputs legacy Riverpod 1.0 StateNotifierProvider boilerplate with manual state mutations and missing loading/error UI states.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Flutter