Skip to content
Skills Library
Programming · Building & coding

flutter-riverpod

/flutter-riverpod

Riverpod 3 with code generation — provider files per feature (providers/<x>_provider.dart, repositories/<x>_repository_provider.dart), functional Future providers that unwrap repository Results with switch and throw the failure, keepAlive caching, derived providers awaiting other.future, family parameters, parallel fetches with record .wait, live refresh with a Timer and invalidateSelf, selection Notifiers, async-created values injected with overrideWithValue, the retry policy on ProviderScope, AsyncValue consumed with error-first switch patterns (never .when/.maybeWhen/.whenData/.map), refres

Licence
MIT
Last repository change
05.11.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 05.11.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Riverpod 3 with code generation — provider files per feature (providers/<x>_provider.dart, repositories/<x>_repository_provider.dart), functional Future providers that unwrap repository Results with switch and throw the failure, keepAlive caching, derived providers awaiting other.future, family parameters, parallel fetches with record .wait, live refresh with a Timer and invalidateSelf, selection Notifiers, async-created values injected with overrideWithValue, the retry policy on ProviderScope, AsyncValue consumed with error-first switch patterns (never .when/.maybeWhen/.whenData/.map), refres

Original author description

Riverpod 3 with code generation — provider files per feature (providers/<x>_provider.dart, repositories/<x>_repository_provider.dart), functional Future providers that unwrap repository Results with switch and throw the failure, keepAlive caching, derived providers awaiting other.future, family parameters, parallel fetches with record .wait, live refresh with a Timer and invalidateSelf, selection Notifiers, async-created values injected with overrideWithValue, the retry policy on ProviderScope, AsyncValue consumed with error-first switch patterns (never .when/.maybeWhen/.whenData/.map), refres

How it works

  1. Setup
  2. Where providers live
  3. Fetching: unwrap the repository's Result
  4. Caching and derived providers
  5. Parallel fetches
  6. Live refresh
  7. Selection Notifiers
  8. Async-created values: create in main.dart, inject with overrideWithValue
  9. Retry
  10. Consuming in widgets
Original SKILL.md headings · 318 lines, 1,309 words
SKILL.md preview
---
name: flutter-riverpod
description: "Riverpod 3 with code generation — provider files per feature (providers/<x>_provider.dart, repositories/<x>_repository_provider.dart), functional Future providers that unwrap repository Results with switch and throw the failure, keepAlive caching, derived providers awaiting other.future, family parameters, parallel fetches with record .wait, live refresh with a Timer and invalidateSelf, selection Notifiers, async-created values injected with overrideWithValue, the retry policy on ProviderScope, AsyncValue consumed with error-first switch patterns (never .when/.maybeWhen/.whenData/.map), refresh indicators with isLoading/hasValue, ref.watch vs read vs listen, and testing with ProviderContainer.test and noRetry. Use when the project imports flutter_riverpod or riverpod, or when writing, reviewing, or testing providers."
license: MIT
metadata:
  author: Matiss Kalnins
  version: "0.5.0"
---

**Persona:** You write generated Riverpod providers that are small and boring. Repositories return `Result`, providers turn it into plain values, and widgets switch on `AsyncValue`. Legacy `StateNotifier`, `StateProvider`, and `ChangeNotifierProvider` are out.

## Setup

```yaml
dependencies:
  flutter_riverpod: ^3.4.3
  riverpod_annotation: ^4.0.7
dev_dependencies:
  build_runner: ^2.16.2
  riverpod_generator: ^4.0.9
  riverpod_lint: ^3.1.9
```

```yaml
# analysis_options.yaml (top level)
plugins:
  riverpod_lint: ^3.1.9
```

- Provider files import `package:riverpod_annotation/riverpod_annotation.dart`, which re-exports `Ref`. Widgets import `flutter_riverpod`.
- Run `dart run build_runner watch -d` while developing. The `.g.dart` files are gitignored.

## Where providers live

| File | Holds |
| --- | --- |
| `lib/src/<feature>/repositories/<x>_repository_provider.dart` | The keepAlive repository provider, building its Retrofit API inline |
| `lib/src/<feature>/providers/<x>_provider.dart` | Fetching providers, derived providers, and selection Notifiers. One file can hold closely related providers |
| `lib/src/core/...` | Infrastructure: `dioProvider`, `routerProvider`, `sharedPreferencesProvider`, `darkThemeProvider` |

## Fetching: unwrap the repository's Result

```dart
/// Bio, stats and recent games for the player with id [playerId].
@riverpod
Future<PlayerLanding> player(Ref ref, int playerId) async {
  final repo = ref.watch(playersRepositoryProvider);

  final Result<PlayerLanding> result = await repo.getPlayer(playerId);
  return switch (result) {
    Ok(:final value) => value,
    Err(:final failure) => throw failure,
  };
}
```

- An `Err`'s failure is thrown, so the provider becomes `AsyncError(failure)` and widgets match on the typed failure. This is the one sanctioned `throw` in app code (see `dart-error-handling`).
- Family parameters are plain function parameters (`player(Ref ref, int playerId)`, used as `playerProvider(playerId)`). They must have value equality.

## Caching and derived providers

Fetch once with keepAlive, then derive cheap views from the cached data:

```dart
/// Number of players fetched per leaderboard.
const int leaderboardLimit = 15;

/// Every skater leaderboard in one request, kept so switching categories
/// doesn't refetch.
@Riverpod(keepAlive: true)
Future<SkaterLeadersResponse> skaterLeaders(Ref ref) async {
  final repo = ref.watch(leadersRepositoryProvider);

  final Result<SkaterLeadersResponse> result = await repo
      .getCurrentSkaterLeaders(limit: leaderboardLimit);
  return switch (result) {
    Ok(:final value) => value,
    Err(:final failure) => throw failure,
  };
}

/// The leaderboard for the selected [leadersCategoryProvider], picked from
/// the cached [skaterLeadersProvider] or [goalieLeadersProvider].
@riverpod
Future<Leaderboard> leaders(Ref ref) async {
  final LeaderCategory category = ref.watch(leadersCategoryProvider);

  return (
    category: category,
    leaders: switch (category) {
      SkaterLeaderCategory() => (await ref.watch(skaterLeadersProvider.future))[category],
      GoalieLeaderCategory() => (await ref.watch(goalieLeadersProvider.future))[category],
    },
  );
}
```

- Derived providers return the selection together with its data (a record such as `Leaderboard`). The UI can then keep showing the old list, labelled correctly, while the next one loads.
- Grouping and sorting belong in derived providers, not widgets. Local mutable collections are fine while computing the result.

## Parallel fetches

```dart
@riverpod
Future<GameDetails> gameDetails(Ref ref, int gameId) async {
  final repo = ref.watch(gameCenterRepositoryProvider);

  final (Result<GameLanding> landing, Result<GameRightRail> rightRail) = await (
    repo.getLanding(gameId),
    repo.getRightRail(gameId),
  ).wait;

  return (
    landing: switch (landing) {
      Ok(:final value) => value,
      Err(:final failure) => throw failure,
    },
    rightRail: switch (rightRail) {
      Ok(:final value) => value,
      Err(:final failure) => throw failure,
    },
  );
}
```

## Live refresh

While data is changing by the minute, refetch on a timer:

```dart
final bool anyLive = schedule.gameWeek
    .expand((day) => day.games)
    .any((game) => game.gameState.isOngoing);
if (anyLive) {
  final Timer timer = Timer(liveRefreshInterval, ref.invalidateSelf);
  ref.onDispose(timer.cancel);
}

return schedule;
```

The interval is a constant next to the model it relates to (`const Duration liveRefreshInterval = Duration(seconds: 60);`).

## Selection Notifiers

UI selections (a tab, a view mode, a category) are small Notifiers with `select`-style methods:

```dart
/// Whether the standings are shown by division or league-wide.
@riverpod
class StandingsViewSelection extends _$StandingsViewSelection {
  @override
  StandingsView build() => .division;

  void select(StandingsView view) {
    state = view;
  }
}

/// The leaderboard category the user picked. Remembers the last pick in each
/// [LeaderGroup], so switching back returns to the category the user left it on.
@riverpod
class LeadersCategory extends _$LeadersCategory {
  SkaterLeaderCategory _skater = .goals;
  GoalieLeaderCategory _goalie = .wins;

  @override
  LeaderCategory build() => _skater;

  void select(LeaderCategory category) {
    switch (category) {
      case SkaterLeaderCategory():
        _skater = category;
      case GoalieLeaderCategory():
        _goalie = category;
    }
    state = category;
  }

  void selectGroup(LeaderGroup group) {
    state = switch (group) {
      .skaters => _skater,
      .goalies => _goalie,
    };
  }
}
```

- `state` is an immutable value: an enum, a record, a freezed class, or an `IList`. Replace it, never mutate it.
- **Private fields are allowed** for remembered choices that aren't what the UI shows (like `_skater` above). Everything the UI reads goes through `state`.

## Async-created values: create in main.dart, inject with overrideWithValue

```dart
/// Key-value storage, created once in `main` before the app starts and
/// injected with `overrideWithValue`.
@Riverpod(keepAlive: true)
SharedPreferencesWithCache sharedPreferences(Ref ref) =>
    throw UnimplementedError("Overridden in main with overrideWithValue");
```

`main.dart` creates the value and passes `sharedPreferencesProvider.overrideWithValue(preferences)` to the root `ProviderScope` (see `flutter-project-layout`). Everything that depends on it, like `DarkTheme.build`, reads it synchronously. Don't turn such values into `FutureProvider`s.

## Retry

The root `ProviderScope` retries only transient failures:

```dart
retry: (retryCount, error) => switch (error) {
  Offline() || TimeoutFailure() when retryCount < 3 => Duration(seconds: 1 << retryCount),
  _ => null,
},
```

Tests pass `retry: noRetry`, so failures settle immediately.

## Consuming in widgets

**Always `switch` on `AsyncValue`, and match the error first.** Never use `.when`, `.maybeWhen`, `.whenOrNull`, `.whenData`, `.map`, `.maybeMap`, or `.mapOrNull`.

```dart
class const LeadersList({super.key}) extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final leadersState = ref.watch(leadersProvider);

    return switch (leadersState) {
      AsyncValue(:final Object error) => ErrorView(
        error: error,
        onRetry: () {
          // The failed request is in the cached group providers.
          ref
            ..invalidate(skaterLeadersProvider)
            ..invalidate(goalieLeadersProvider);
        },
      ),
      AsyncValue(value: (:final LeaderCategory category, :final IList<StatLeader> leaders)) =>
        ListView.separated(
          // Keyed by the loaded category, so a new leaderboard starts at the top.
          key: ValueKey(category),
          itemBuilder: (context, i) => LeaderRow(rank: i + 1, leader: leaders[i], category: category),
          separatorBuilder: (context, i) => const Divider(height: 1),
          itemCount: leaders.length,
        ),
      _ => const Center(child: CircularProgressIndicator()),
    };
  }
}
```

- **Order matters:** `AsyncValue(:final Object error)` first, then `AsyncValue(:final T value)` (or record destructuring of `value`), then `_` for loading. While refreshing after data or an error, the previous value or error is still shown.
- Retry by invalidating the provider that actually failed (`ref.invalidate(playerProvider(playerId))`, or the cached source provider).
- **Refresh indicator** while new data loads over old data:

```dart
switch (leadersState) {
  AsyncValue(isLoading: true, hasValue: true) => const LinearProgressIndicator(minHeight: 2),
  _ => const Divider(height: 2),
},
```

- Side effects go in `ref.listen` with a `switch` statement, not in `build`.

## watch / read / listen

| Use | Where |
| --- | --- |
| `ref.watch(p)` | In `build` (widgets and providers). Rebuilds on change |
| `ref.watch(p.future)` | In a provider that needs another provider's loaded value |
| `ref.read(p.notifier).select(x)` | In callbacks (`onSelected`, `onChanged`). Never in `build` |
| `ref.listen(p, (prev, next) {...})` | Side effects: snackbars, navigation |
| `ref.invalidate(p)` / `ref.invalidateSelf()` | Retry buttons and timed refresh |

## Testing

```dart
void main() {
  late FakeLeadersRepository repository;
  late ProviderContainer container;

  setUp(() {
    repository = FakeLeadersRepository(
      skaters: Ok(SkaterLeadersResponse(goals: _board(1), points: _board(2))),
    );
    container = ProviderContainer.test(
      overrides: [leadersRepositoryProvider.overrideWithValue(repository)],
      retry: noRetry,
    );
  });

  Future<Leaderboard> read() {
    container.listen(leadersProvider, (_, _) {});
    return container.read(leadersProvider.future);
  }

  test("switching skater categories fetches skaters once", () async {
    await read();
    container.read(leadersCategoryProvider.notifier).select(SkaterLeaderCategory.points);
    final Leaderboard board = await read();

    expect(board.leaders, _board(2));
    expect(repository.skaterCalls, 1);
  });

  test("a failed fetch surfaces the failure", () async {
    repository.skaters = const Err(Offline());

    await expectLater(read(), throwsA(isA<Offline>()));
  });
}
```

- Override repository providers with fakes from `test/helpers/fakes.dart`, and pass `retry: noRetry`.
- `container.listen(p, (_, _) {})` keeps an autoDispose provider alive while the test reads `p.future`.
- Use `fake_async` for timer-based refresh (see `flutter-testing`).

## Anti-patterns

- `.when` / `.maybeWhen` / `.whenOrNull` / `.whenData` / `.map` on `AsyncValue`, instead of a `switch`.
- Returning `Result` from a provider (`AsyncValue<Result<T>>`). Unwrap it.
- `AsyncValue.guard`. `Result.guard` in the repository already caught the error.
- Calling a Retrofit API or a repository from a widget. Go through a provider.
- `ref.read` in `build`, or `ref.watch` in callbacks.
- `FutureProvider`s for values that `main.dart` can create before `runApp`.
- The legacy `StateProvider`/`StateNotifierProvider`/`ChangeNotifierProvider` (in `package:flutter_riverpod/legacy.dart` since 3.0).

Versions

The database has no other skills named flutter-riverpod.

Database snapshot: 13.11.2026 · package version 67d4790aa21a (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100riverpod-patterns
    This skill provides Riverpod state management patterns and best practices for Flutter applications. Use when reviewing or writing Riverpod providers, AsyncValue handling, ref usage, or provider lifecycle management.
  • 100flutter-state-to-riverpod
    Use when migrating a Flutter app from setState, Provider or ChangeNotifier to Riverpod, or when writing providers, Notifiers and AsyncNotifiers. Triggers on "migrate to Riverpod", "AsyncNotifier", "ProviderScope", "ConsumerWidget", "ref.watch".
  • 100flutter-riverpod-expert
    Design, implement, refactor, migrate, or review Flutter state management with Riverpod using the manual provider patterns shown in this repository's real Flutter projects: explicit datasource and repository providers, split state and operation providers, auth stream listeners,…
  • 100riverpod
    Use when working with Flutter Riverpod state management. Covers providers, consumers, refs, containers, overrides, async state, code generation, testing, and safe defaults.
  • 100flutter-riverpod-state-management
    Implement reactive state management using Riverpod 3.x with code generation in Flutter. Use when defining providers, building AsyncNotifiers, or overriding providers in tests.
  • 100flutter-architecture
    Provides Flutter app architecture patterns with feature-first structure, clean architecture, and state management (Bloc, Riverpod, Provider). Use when user asks about Flutter project structure, state management selection, dependency injection, or designing Flutter app architecture.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.