본문으로 건너뛰기
cccskills
무료GitHub에 공개

implementing-riverpod

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.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(4)

  • SKILL.md7.2 KB
  • references/PITFALLS.md6.7 KB
  • references/riverpod.md18.1 KB
  • references/state-management-overview.md6.5 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

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

Manual only (no code generation):

dependencies:
  flutter_riverpod: ^3.3.1

Phase 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: counterProvider

AsyncNotifier (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: todoListProvider

FutureProvider 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


Constraints

  • No BuildContext in providers: Access state via ref only.
  • Compile-time safety: Use @riverpod code generation; catches errors at build time.
  • Immutable state: Keep state immutable; use Freezed for complex models. v3.0 uses == for all state comparisons — implement operator == or use Freezed.
  • Auto-dispose by default: Code-gen providers auto-dispose unless marked keepAlive: true.
  • Ref lifecycle: Never store ref in a variable or pass it outside provider scope.
  • AsyncValue.guard: Always wrap async state mutations in AsyncValue.guard().
  • ⚠️ ref.mounted: Always check ref.mounted after await before updating state.
  • ⚠️ ref.onDispose: Cancel timers, streams, and HTTP requests in ref.onDispose.
  • ⚠️ ref.read in callbacks: Use ref.read in event handlers; ref.watch only in build().
  • ⚠️ 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 Provider with ref.onDispose.
  • Scoped rebuilds: Prefer Consumer over ConsumerWidget; use select() for field-level precision.

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Declarative animation patterns using flutter_animate v4.5.x with composable effects (fade, scale, slide, shimmer, shake, blur), GLSL fragment shaders, and scroll-synchronized animations. Use this skill for adding UI animations and transitions, building staggered or sequenced effects, creating custom animation effects, fixing animation jank or performance issues, implementing shimmer loading states, or adding scroll-driven animations. Supports delays, curves, adaptive effects, and easy extension method chaining (.animate()).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Dart 3 modern features (through 3.10) and Effective Dart best practices including records, patterns, sealed classes, dot shorthands, null-aware collection elements, and wildcard variables. Use when adopting Dart 3.7+ syntax, using dot shorthands for enums or static members, using null-aware elements in lists or maps, using wildcard _ parameters, improving code quality, or reviewing Dart code conventions.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Expert-level guidance for Flutter production applications: architecture decisions (Clean/Layered/Hexagonal/Feature-First), advanced state management (BLoC/Riverpod/GetX), performance optimization (eliminating jank, memory profiling, reducing rebuild overhead), code review with design pattern enforcement, scalability assessments, native platform integration (MethodChannel/EventChannel/FFI), complex UI challenges (custom render objects, slivers), testing strategies (unit/widget/integration/golden), CI/CD pipeline architecture, build optimization, and accessibility compliance. Triggers: 'architecture decision', 'design pattern', 'performance issue', 'code review', 'production problem', 'scaling concerns', 'best practices', 'technical debt', 'refactoring strategy'. Essential for complex enterprise apps, critical production debugging, architectural refactors, or when choosing between competing technical approaches.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Builds SEO-friendly web applications with Dart using the Jaspr framework. Use when creating Dart-based websites, blogs, or landing pages requiring semantic HTML output; implementing server-side rendering (SSR) or static site generation (SSG); adding Tailwind CSS via jaspr_tailwind; routing with jaspr_router; testing components with jaspr_test; or building full-stack Dart web apps where Flutter Web's canvas rendering is unsuitable.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

shadcn_flutter UI component library for building accessible, themed Flutter interfaces. Use when integrating shadcn components, configuring design system theming, or building consistent widget layouts.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Configures Codemagic CI/CD pipelines for Flutter using `codemagic.yaml`. Use when setting up automated Flutter builds on Codemagic, configuring iOS code signing without Fastlane Match, deploying to App Store Connect or Google Play from Codemagic, caching pub dependencies in Codemagic, setting up encrypted environment variable groups, running tests with Codemagic's test dashboard, or choosing between Codemagic and GitHub Actions + Fastlane for a Flutter CI/CD pipeline.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

Poorgramer-Zack/dart-expert-skills72026년 8월 11일 업데이트

Poorgramer-Zack의 스킬 모두 보기

이 스킬의 문제 신고