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

Flutter 3.27 & Riverpod 2.6 Codegen, Reactivity Safety, and AutoDispose Invariants

Enforces strict architectural boundaries for Riverpod 2.6 code generation within Flutter 3.27 projects. Mandates typed code-generated providers (@riverpod), explicitly manages AutoDispose lifecycles with ref.onDispose cancellation, and strictly prohibits invalid ref.watch invocations inside asynchronous execution blocks or event callbacks.

Prohibited Anti-Pattern: Unsafe ref.watch Invocations in Async Closures and Unmanaged AutoDispose Network Thrashing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Flutter 3.27 & Riverpod 2.6 Codegen, Reactivity Safety, and AutoDispose Invariants - Enforces strict architectural boundaries for Riverpod 2.6 code generation within Flutter 3.27 projects. Mandates typed code-generated providers (@riverpod), explicitly manages AutoDispose lifecycles with ref.onDispose cancellation, and strictly prohibits invalid ref.watch invocations inside asynchronous execution blocks or event callbacks.
globs: lib/**/*.dart, test/**/*.dart
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/flutter-riverpod-codegen-reactivity-lifecycle"
---

# Flutter 3.27 & Riverpod 2.6 Codegen, Reactivity Safety, and AutoDispose Invariants

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsafe ref.watch Invocations in Async Closures and Unmanaged AutoDispose Network Thrashing

## System Constraints
You are a Principal Mobile Architect enforcing Flutter 3.27 and Riverpod 2.6 code generation standards. Enforce the exclusive use of @riverpod code-generated providers over legacy manual provider declarations. Mandate precise distinction between ref.watch (declarative build/provider body) and ref.read (imperative callbacks). Require explicit lifecycle cleanup (ref.onDispose) and prevent async race conditions across AutoDispose boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS use Riverpod 2.6 code generation via `@riverpod` annotations and declare `part '<filename>.g.dart';` in every provider definition file.
- Engineers MUST NOT manually instantiate legacy `ChangeNotifierProvider`, `StateNotifierProvider`, or raw untyped `FutureProvider` classes.
- Code MUST strictly invoke `ref.watch` synchronously within `build()` methods or reactive provider bodies; invoking `ref.watch` inside asynchronous callbacks, event handlers, or post-await frames is strictly prohibited.
- Engineers MUST use `ref.read` solely inside user-driven or lifecycle imperative callbacks (e.g., `onPressed`, `onTap`, `initState` queues).
- Services and async providers MUST register cleanup logic with `ref.onDispose()` to abort pending HTTP requests or tear down active streaming subscriptions upon AutoDispose trigger.
- Providers maintaining persistent application state (such as auth sessions or connectivity channels) MUST explicitly declare `@Riverpod(keepAlive: true)` to avoid catastrophic re-initialization cycles.
- Components MUST NEVER depend on `ref.watch` inside conditional loops or branches where provider keys dynamically fluctuate between frames.

## Bad vs Good Implementations
### AsyncNotifier Codegen with AutoDispose Cleanup vs Manual Legacy Provider

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declares legacy StateNotifierProvider instead of @riverpod codegen. Lacks an HTTP cancellation token linked to AutoDispose lifecycle, causing resource leaks. Additionally, invokes ref.watch inside an async button callback, which is an anti-pattern that violates Riverpod reactivity contracts.
```dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;

// ANTI-PATTERN: Manual legacy StateNotifierProvider without cancellation safety
final userProfileProvider = StateNotifierProvider.autoDispose<UserProfileNotifier, AsyncValue<User>>((ref) {
  return UserProfileNotifier(ref);
});

class UserProfileNotifier extends StateNotifier<AsyncValue<User>> {
  final Ref ref;
  UserProfileNotifier(this.ref) : super(const AsyncLoading()) {
    loadUser();
  }

  Future<void> loadUser() async {
    // Leaks HTTP connection if disposed mid-flight
    final response = await http.get(Uri.parse('https://api.example.com/user'));
    state = AsyncData(User.fromJson(response.body));
  }
}

class UserView extends ConsumerWidget {
  const UserView({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return ElevatedButton(
      onPressed: () async {
        // ANTI-PATTERN: ref.watch inside an asynchronous event handler
        final user = ref.watch(userProfileProvider);
        await syncTelemetry(user);
      },
      child: const Text('Sync'),
    );
  }
}
```

#### Production Standard (Correct)
> **Standard**: Uses Riverpod 2.6 `@riverpod` code generation with _$UserProfile. Cleans up pending I/O operations via `ref.onDispose` and `CancelToken`. Consumes state reactively using `ref.watch` synchronously in `build()` and mutations imperatively via `ref.read` in `onPressed`.
```dart
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'user_profile.g.dart';

@riverpod
class UserProfile extends _$UserProfile {
  @override
  FutureOr<User> build() async {
    final cancelToken = CancelToken();
    ref.onDispose(() => cancelToken.cancel('Provider disposed'));

    final dio = ref.watch(dioClientProvider);
    final response = await dio.get(
      '/user',
      cancelToken: cancelToken,
    );
    return User.fromJson(response.data as Map<String, dynamic>);
  }

  Future<void> updateBio(String bio) async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(() async {
      final dio = ref.read(dioClientProvider);
      final response = await dio.patch('/user', data: {'bio': bio});
      return User.fromJson(response.data as Map<String, dynamic>);
    });
  }
}

class UserView extends ConsumerWidget {
  const UserView({super.key});

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

    return userAsync.when(
      loading: () => const CircularProgressIndicator(),
      error: (err, stack) => Text('Error: $err'),
      data: (user) => ElevatedButton(
        onPressed: () => ref.read(userProfileProvider.notifier).updateBio('New Bio'),
        child: Text('Update Bio for ${user.name}'),
      ),
    );
  }
}
```

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 3.27 & Riverpod 2.6 Codegen, Reactivity Safety, and AutoDispose Invariants

Flutter 3.27 & Riverpod 2.6 Codegen, Reactivity Safety, and AutoDispose Invariants defines an industrial-grade behavioral standard for mobile engineering. Enforces strict architectural boundaries for Riverpod 2.6 code generation within Flutter 3.27 projects. Mandates typed code-generated providers (@riverpod), explicitly manages AutoDispose lifecycles with ref.onDispose cancellation, and strictly prohibits invalid ref.watch invocations inside asynchronous execution blocks or event callbacks. 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: Unsafe ref.watch Invocations in Async Closures and Unmanaged AutoDispose Network Thrashing 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 DriftUnsafe ref.watch Invocations in Async Closures and Unmanaged AutoDispose Network ThrashingCritical
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

Engineers MUST ALWAYS use Riverpod 2.6 code generation via `@riverpod` annotations and declare `part '<filename>.g.dart'

Engineers MUST ALWAYS use Riverpod 2.6 code generation via `@riverpod` annotations and declare `part '<filename>.g.dart';` in every provider definition file.

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

Engineers MUST NOT manually instantiate legacy `ChangeNotifierProvider`, `StateNotifierProvider`, or raw untyped `FutureProvider` classes.

Engineers MUST NOT manually instantiate legacy `ChangeNotifierProvider`, `StateNotifierProvider`, or raw untyped `FutureProvider` 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.
3

Code MUST strictly invoke `ref.watch` synchronously within `build()` methods or reactive provider bodies

Code MUST strictly invoke `ref.watch` synchronously within `build()` methods or reactive provider bodies; invoking `ref.watch` inside asynchronous callbacks, event handlers, or post-await frames is strictly prohibited.

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

Engineers MUST use `ref.read` solely inside user-driven or lifecycle imperative callbacks (e.g., `onPressed`, `onTap`, `initState` queues).

Engineers MUST use `ref.read` solely inside user-driven or lifecycle imperative callbacks (e.g., `onPressed`, `onTap`, `initState` queues).

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

Services and async providers MUST register cleanup logic with `ref.onDispose()` to abort pending HTTP requests or tear down active streaming subscriptions upon AutoDispose trigger.

Services and async providers MUST register cleanup logic with `ref.onDispose()` to abort pending HTTP requests or tear down active streaming subscriptions upon AutoDispose trigger.

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

Providers maintaining persistent application state (such as auth sessions or connectivity channels) MUST explicitly declare `@Riverpod(keepAlive

Providers maintaining persistent application state (such as auth sessions or connectivity channels) MUST explicitly declare `@Riverpod(keepAlive: true)` to avoid catastrophic re-initialization cycles.

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

Components MUST NEVER depend on `ref.watch` inside conditional loops or branches where provider keys dynamically fluctuate between frames.

Components MUST NEVER depend on `ref.watch` inside conditional loops or branches where provider keys dynamically fluctuate between frames.

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 3.27 & Riverpod 2.6 Codegen, Reactivity Safety, and AutoDispose Invariants critical for AI coding assistants?

Enforces strict architectural boundaries for Riverpod 2.6 code generation within Flutter 3.27 projects. Mandates typed code-generated providers (@riverpod), explicitly manages AutoDispose lifecycles with ref.onDispose cancellation, and strictly prohibits invalid ref.watch invocations inside asynchronous execution blocks or event callbacks. 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 (Unsafe ref.watch Invocations in Async Closures and Unmanaged AutoDispose Network Thrashing) 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