Source profileQuality 91/100

evanca/flutter-ai-rules/skills/riverpod/SKILL.md

riverpod

Use when setting up providers, combining requests, managing state disposal, passing arguments, performing side effects, or testing providers (Riverpod).

Source repository stars
620
Declared platforms
0
Static risk flags
0
Last source update
2026-08-27
Source checked
2026-08-28

Decision brief

What it does: where it fits

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

Best for

  • Use when setting up providers, combining requests, managing state disposal, passing arguments, performing side effects, or testing providers (Riverpod).

Not for

  • Tasks that require unconfirmed production actions or broad system permissions.
  • Environments where the pinned source and install steps cannot be inspected.

Compatibility matrix

Platform support, with evidence labels

PlatformStatusEvidenceWhat to check
CodexNot declaredNo explicit evidencePortability before use
Claude CodeNot declaredNo explicit evidencePortability before use
CursorNot declaredNo explicit evidencePortability before use
Gemini CLINot declaredNo explicit evidencePortability before use
Open the compatibility checker

Installation

Inspect first. Install second.

The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.

Source-detected install commandSource
npx skills add https://github.com/evanca/flutter-ai-rules --skill "skills/riverpod"
Safe inspection promptEditorial

Inspect the Agent Skill "riverpod" from https://github.com/evanca/flutter-ai-rules/blob/713576e02b6a17de4cc5a95ad55bdcca3a0827a6/skills/riverpod/SKILL.md at commit 713576e02b6a17de4cc5a95ad55bdcca3a0827a6. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.

Workflow

What the source asks the agent to do

  1. 01

    1. Setup

    Wrap your app with ProviderScope directly in runApp — never inside MyApp.

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

    2. Defining Providers

    Define all providers as final top-level variables.

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

    3. Using Ref

    Never call ref.watch inside callbacks, listeners, or Notifier methods.

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

    4. Combining Providers

    Use ref.watch(asyncProvider.future) to await an async provider's resolved value.

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

    5. Passing Arguments (Families)

    Always enable autoDispose for parameterized providers to prevent memory leaks.

    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.

Permission review

Static risk signals and limitations

No configured static risk pattern was detected

This is not proof of safety. Runtime behavior, indirect dependencies, and hidden external systems are outside the static scan.

Evidence record

Why each signal appears

EvidenceSourceComputedTestedEditorial
SignalValueEvidence typeMeaning
Quality score91/100ComputedDocumentation, specificity, maintenance, and trust rules
Repository stars620SourceRepository attention, not individual Skill quality
Compatibility0 platformsSourceDeclared in the catalog source record
Usage guideautomated source guideEditorialGenerated or reviewed according to the visible evidence level

Pinned source

Provenance and original SKILL.md

Repository
evanca/flutter-ai-rules
Skill path
skills/riverpod/SKILL.md
Commit
713576e02b6a17de4cc5a95ad55bdcca3a0827a6
License
MIT
Collected
2026-08-28
Default branch
main
View the original SKILL.md

Riverpod Skill

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


1. Setup

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

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

MethodUse for
ref.watchReactively listen — rebuilds when value changes. Use during build phase only.
ref.readOne-time access — use in callbacks/Notifier methods, not in build.
ref.listenImperative subscription — prefer ref.watch where possible.
ref.onDisposeCleanup when provider state is destroyed.
// 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

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

@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.
// 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:

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

@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

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

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

Frequently asked questions

What to verify before installation and use

What does the riverpod source document cover?

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

How do I install riverpod?

The source record exposes this install command: npx skills add https://github.com/evanca/flutter-ai-rules --skill "skills/riverpod". Inspect the command and pinned source before running it.

Alternatives

Compare before choosing

Computed 10045,960

coreyhaines31/marketingskills

ab-testing

When the user wants to plan, design, or implement an A/B test or experiment, or build a growth experimentation program. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "should I test this," "which version is better," "test two versions," "statistical significance," "how long should I run this test," "growth experiments," "experiment velocity," "experiment backlog," "ICE score," "experimentation program

Computed 10029,236

garrytan/gbrain

bulk-ingestion

End-to-end discipline for turning any large data source (audio libraries, email takeouts, document corpora, chat exports, API dumps) into brain pages at scale. The lifecycle spine: SCHEMA → ACCESS → TRIAL → EVALUATE → IMPROVE → CODIFY → TEST → SKILLIFY → BULK → MONITOR. State is tracked in a durable JSON manifest (see MANIFEST-PATTERN.md) so any crash, session boundary, or subagent fan-out resumes from ground truth instead of memory.

Computed 10025,136

alirezarezvani/claude-skills

app-store-optimization

App Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklist

Computed 10014,706

prowler-cloud/prowler

postgresql-indexing

PostgreSQL indexing best practices for Prowler: index design, partial indexes, partitioned table indexing, EXPLAIN ANALYZE validation, concurrent operations, monitoring, and maintenance. Trigger: When creating or modifying PostgreSQL indexes, analyzing query performance with EXPLAIN, debugging slow queries, reviewing index usage statistics, reindexing, dropping indexes, or working with partitioned table indexes. Also trigger when discussing index strategies, partial indexes, or index maintenance