flutter-idioms

SkillDev tools

Flutter Riverpod 3, freezed, go_router, const widgets, repository pattern.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the flutter-idioms skill

What this skill tells your AI

The instructions your AI receives, as published by irahardianto/awesome-agv in .agents/skills/flutter-idioms/SKILL.md and read by ahel’s review.

Flutter Idioms and Patterns (Riverpod 3)

Core Philosophy

Flutter is a UI toolkit first — performance is a first-class concern. const widgets and immutable data keep the render tree efficient. Riverpod 3 is the canonical state management solution: compile-safe, testable without BuildContext, no implicit global state, and with automatic retry and pause/resume built in.

Code generation is mandatory. All providers must use @riverpod / @Riverpod(keepAlive: true) annotations with riverpod_generator and build_runner. This catches type errors, missing overrides, and broken provider graphs at compile time — bugs are caught before they reach users.

Required dependencies:

# pubspec.yaml
dependencies:
  flutter_riverpod: 3.2.1
  riverpod_annotation: 4.0.2

dev_dependencies:
  riverpod_generator: 4.0.3
  build_runner: # latest
  riverpod_lint: # latest

Scope: This file covers Flutter/Dart coding idioms. For file and folder layout, see references/project-structure.md. For test naming, see testing-strategy.md. For general error handling principles, see error-handling-principles.md.


const Constructors — Everywhere

Make every widget const when possible. const widgets are created once and never rebuilt unless their inputs change — this is Flutter's most impactful performance optimization.

// ✅ const constructor — widget is rebuild-safe
class TaskCard extends StatelessWidget {
    const TaskCard({super.key, required this.task});
    final Task task;
    // ...
}

// Usage — compile-time constant
const TaskCard(task: myTask)

// ❌ Missing const — rebuilt on every parent rebuild
TaskCard(task: myTask)

Rules:

  • Every StatelessWidget that has no mutable state must have a const constructor
  • Pass const keyword at the call site, not just the definition
  • Lint rule prefer_const_constructors must be enabled in analysis_options.yaml

Widget Decomposition

Large build methods are the primary source of performance problems and unmaintainable UI code.

  1. Extract a new widget when a subtree has distinct responsibilities

    // ❌ Everything in one build method
    @override
    Widget build(BuildContext context) {
        return Column(children: [
            // 30 lines of header...
            // 50 lines of list...
            // 20 lines of footer...
        ]);
    }
    
    // ✅ Each subtree is a named widget with a const constructor
    @override
    Widget build(BuildContext context) {
        return Column(children: [
            const TaskHeader(),
            const TaskList(),
            const TaskFooter(),
        ]);
    }
    
  2. Never use builder methods (_buildHeader()) as a substitute for extracting widgets

    • Builder methods do not benefit from const and always rerun on parent rebuild
    • Extract a proper StatelessWidget or ConsumerWidget instead
  3. Keep build methods under ~30 lines — if longer, decompose


Immutable Data with freezed

All domain models must be immutable. Use the freezed package for:

  • Immutable value objects with copyWith
  • Union/sealed types (loading, success, error states)
  • Generated ==, hashCode, and toString
// task/models/task.dart
@freezed
class Task with _$Task {
    const factory Task({
        required String id,
        required String title,
        @Default(TaskStatus.pending) TaskStatus status,
        DateTime? dueDate,
    }) = _Task;

    factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
}

// Usage — immutable update via copyWith
final updated = task.copyWith(status: TaskStatus.done);

// ❌ Never mutate a model directly
task.status = TaskStatus.done; // compile error — field is final

Rules:

  • All domain models use @freezed
  • Never expose mutable fields on domain models
  • Run dart run build_runner build after changing freezed models

Provider Decision Tree

Use this tree to pick the correct provider pattern. Follow it top-to-bottom — the first match wins.

Does the provider have side-effects (create/update/delete)? ──> YES ──┐
    │                                                                  │
    NO                                                                 │
    │                                                             Is it async?
    │                                                              │       │
Is it async?                                                      YES     NO
    │       │                                                      │       │
   YES     NO                                                     ▼       ▼
    │       │                                              @riverpod   @riverpod
    ▼       ▼                                              class       class
@riverpod  @riverpod                                       (AsyncNotifier) (Notifier)
function   function
(FutureProvider) (Provider)

Decision summary:

Has side-effects?Async?PatternProvider type generated
NoNo@riverpod functionProvider
NoYes@riverpod async functionFutureProvider
NoStream@riverpod Stream functionStreamProvider
YesNo@riverpod classNotifierProvider
YesYes@riverpod class with Future buildAsyncNotifierProvider
YesStream@riverpod class with Stream buildStreamNotifierProvider

Riverpod — State Management

Riverpod 3 is the only state management solution used in this project. Do not introduce BLoC, Cubit, Provider (package:provider), or GetX.

For file layout of state/ directories, see references/project-structure.md.

App Entry Point — ProviderScope

Every Flutter app using Riverpod must wrap the root widget in ProviderScope. This creates the ProviderContainer that powers all providers in the widget tree.

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
    runApp(const ProviderScope(child: MyApp()));
}

Rules:

  • Exactly one ProviderScope at the app root — never nest ProviderScope widgets
  • Use overrides: parameter only in tests (see Testing section)
  • For retry configuration, pass retry: to the root ProviderScope (see Runtime Behaviors)
Provider Definition — Class-Based (Side-Effects)

Use class-based providers when the provider needs methods to modify state.

// Synchronous notifier — e.g., a filter or toggle
@riverpod
class TaskFilter extends _$TaskFilter {
    @override
    TaskFilterState build() {
        return const TaskFilterState();
    }

    void setStatus(TaskStatus? status) {
        state = state.copyWith(status: status);
    }

    void toggleShowCompleted() {
        state = state.copyWith(showCompleted: !state.showCompleted);
    }
}
// Async notifier — e.g., CRUD operations
@riverpod
class TaskList extends _$TaskList {
    @override
    Future<List<Task>> build() async {
        return ref.watch(taskRepositoryProvider).getTasks();
    }

    Future<void> addTask(CreateTaskRequest request) async {
        state = const AsyncLoading();
        state = await AsyncValue.guard(() async {
            final repo = ref.read(taskRepositoryProvider);
            await repo.createTask(request);
            // REQUIRED: check ref.mounted after every await
            if (!ref.mounted) return state.requireValue;
            return repo.getTasks();
        });
    }

    Future<void> deleteTask(String id) async {
        state = const AsyncLoading();
        state = await AsyncValue.guard(() async {
            final repo = ref.read(taskRepositoryProvider);
            await repo.deleteTask(id);
            if (!ref.mounted) return state.requireValue;
            return repo.getTasks();
        });
    }
}
Provider Definition — Functional (Read-Only / Computed)

Use functional providers for derived values with no side-effects.

// Computed value — filtered task list
@riverpod
List<Task> filteredTasks(Ref ref) {
    final tasks = ref.watch(taskListProvider).valueOrNull ?? [];
    final filter = ref.watch(taskFilterProvider);
    return tasks.where((t) => filter.matches(t)).toList();
}

// Async one-shot read — e.g., fetch a single task
@riverpod
Future<Task> taskDetail(Ref ref, String id) async {
    return ref.watch(taskRepositoryProvider).getById(id);
}

// Stream — real-time data
@riverpod
Stream<List<Task>> taskStream(Ref ref) {
    return ref.watch(taskRepositoryProvider).watchAll();
}

Family providers (parameterized): When a provider takes extra arguments beyond Ref, Riverpod creates a family — each unique argument combination gets its own independent provider instance with its own cache and disposal. With code generation (which we mandate), any number of parameters are supported, including named, optional, and default values. Constraints:

  • All parameters must implement == and hashCode (primitives, freezed models, Dart records all work)
  • Each family member is disposed independently when no listener remains
// ✅ Family with a single key
@riverpod
Future<Task> taskDetail(Ref ref, String id) async {
    return ref.watch(taskRepositoryProvider).getById(id);
}

// ✅ Multiple parameters — fully supported with code generation
@riverpod
Future<List<Task>> projectTasks(Ref ref, String projectId, {TaskStatus? status}) async {
    return ref.watch(taskRepositoryProvider).getByProject(projectId, status: status);
}
// Usage: ref.watch(projectTasksProvider('proj-1', status: TaskStatus.done))
ref.watch vs ref.read
// ✅ ref.watch — subscribes to changes, use inside build() or widget build
final tasks = ref.watch(taskListProvider);

// ✅ ref.read — one-time read, use inside event handlers / notifier actions
Future<void> onSubmit() async {
    await ref.read(taskListProvider.notifier).addTask(request);
}

// ❌ Never use ref.watch inside async functions or event handlers
Future<void> onSubmit() async {
    final tasks = ref.watch(taskListProvider); // WRONG — causes errors
}
Ref.mounted — Mandatory After Awaits

Riverpod 3 throws if you interact with a disposed Ref or Notifier. Always check ref.mounted after any await in a notifier.

Future<void> updateTask(Task task) async {
    final repo = ref.read(taskRepositoryProvider);
    await repo.update(task);

    // REQUIRED: provider may have been disposed during await
    if (!ref.mounted) return;

    state = await AsyncValue.guard(() => repo.getTasks());
}
Auto-Dispose and keepAlive
// ✅ autoDispose is the DEFAULT with code generation (@riverpod)
// Provider is disposed when no consumers are listening
@riverpod
Future<Task> taskDetail(Ref ref, String id) async {
    return ref.watch(taskRepositoryProvider).getById(id);
}

// ✅ Opt into keepAlive explicitly for app-wide, long-lived state
@Riverpod(keepAlive: true)
class AuthState extends _$AuthState {
    @override
    Future<User?> build() async {
        return ref.watch(authRepositoryProvider).getCurrentUser();
    }
}

// ✅ Repositories should also be keepAlive — they hold connection state and
//    should not be re-initialized every time a screen rebuilds
@Riverpod(keepAlive: true)
TaskRepository taskRepository(Ref ref) {
    return TaskRepositoryImpl(apiClient: ref.watch(apiClientProvider));
}

// ❌ Do not set keepAlive: false — that is the default
// ❌ Do not set keepAlive: true for screen-scoped state
Repository Interface Pattern

All data access goes through an abstract repository interface. This is the Flutter expression of the Testability-First architecture (see @.agents/rules/architectural-pattern.md).

// repository/task_repository.dart — Abstract interface (contract)
abstract class TaskRepository {
    Future<List<Task>> getTasks();
    Future<Task> getById(String id);
    Future<void> createTask(CreateTaskRequest request);
    Future<void> deleteTask(String id);
}
// repository/task_repository_impl.dart — Production adapter
class TaskRepositoryImpl implements TaskRepository {
    const TaskRepositoryImpl({required this.apiClient});
    final ApiClient apiClient;

    @override
    Future<List<Task>> getTasks() async {
        final response = await apiClient.get('/tasks');
        return (response.data as List)
            .map((e) => Task.fromJson(e as Map<String, dynamic>))
            .toList();
    }

    @override
    Future<Task> getById(String id) async {
        final response = await apiClient.get('/tasks/$id');
        return Task.fromJson(response.data as Map<String, dynamic>);
    }

    @override
    Future<void> createTask(CreateTaskRequest request) async {
        await apiClient.post('/tasks', data: request.toJson());
    }

    @override
    Future<void> deleteTask(String id) async {
        await apiClient.delete('/tasks/$id');
    }
}
// repository/task_repository_mock.dart — Test adapter
class MockTaskRepository implements TaskRepository {
    final List<Task> _tasks = [];

    @override
    Future<List<Task>> getTasks() async => List.unmodifiable(_tasks);

    @override
    Future<Task> getById(String id) async =>
        _tasks.firstWhere((t) => t.id == id);

    @override
    Future<void> createTask(CreateTaskRequest request) async {
        _tasks.add(Task(id: 'mock-id', title: request.title));
    }

    @override
    Future<void> deleteTask(String id) async {
        _tasks.removeWhere((t) => t.id == id);
    }
}
// Wiring — provider that the rest of the app depends on
@Riverpod(keepAlive: true)
TaskRepository taskRepository(Ref ref) {
    return TaskRepositoryImpl(apiClient: ref.watch(apiClientProvider));
}

// In tests, override with mock:
// taskRepositoryProvider.overrideWith((_) => MockTaskRepository())
ConsumerWidget vs ConsumerStatefulWidget
// ✅ Prefer ConsumerWidget — stateless, simpler
class TaskListView extends ConsumerWidget {
    const TaskListView({super.key});

    @override
    Widget build(BuildContext context, WidgetRef ref) {
        final asyncTasks = ref.watch(taskListProvider);
        return asyncTasks.when(
            data: (tasks) => TaskListBody(tasks: tasks),
            loading: () => const LoadingIndicator(),
            error: (e, _) => ErrorView(error: e),
        );
    }
}

// Use ConsumerStatefulWidget only when local widget state + riverpod is needed

Riverpod 3 — Runtime Behaviors

Automatic Retry

Riverpod 3 automatically retries providers that throw, using exponential backoff. This improves resilience against transient network failures.

// ✅ Default behavior — providers auto-retry on failure
// No action needed for standard use

// ✅ Disable retry for a specific provider when failure is non-transient
@Riverpod(retry: null)
Future<Config> appConfig(Ref ref) async {
    return ref.watch(configRepositoryProvider).load();
}

// ✅ Disable globally via ProviderScope
ProviderScope(
    retry: (_, __) => null, // disable for all providers
    child: const MyApp(),
)

Rules:

  • Leave auto-retry enabled for network/IO operations (transient failures)
  • Disable for operations where retry is unsafe (non-idempotent writes) or pointless (validation errors)
Pause / Resume (Out-of-View Providers)

Riverpod 3 automatically pauses provider listeners when the consuming widget is no longer visible. When the widget becomes visible again, listeners resume.

This is automatic — no action needed. Be aware of it when debugging.

ProviderException Wrapping

When a provider fails, reading it in Riverpod 3 throws a ProviderException wrapping the original error, not the raw exception.

// ✅ Catch ProviderException when reading providers that may fail
try {
    final value = container.read(myProvider);
} on ProviderException catch (e) {
    // e.exception contains the original error
    // e.provider contains which provider failed
}
// ✅ Assert on provider failure in tests
expect(
    () => container.read(myProvider),
    throwsA(isA<ProviderException>()),
);
State Change Detection (==)

Riverpod 3 uses the == operator (not identical) to determine if state changed and rebuilds are needed. This means:

  • freezed models work correctly out of the box (generated ==)
  • Custom models must implement == / hashCode or use freezed
  • Override updateShouldNotify on a Notifier for custom comparison logic

Async Patterns

  1. Always handle all three AsyncValue states: data, loading, error

    // ✅ Exhaustive
    asyncValue.when(
        data: (data) => DataWidget(data: data),
        loading: () => const CircularProgressIndicator(),
        error: (err, stack) => ErrorText(err.toString()),
    );
    
  2. Surfacing notifier errors to UI — use when(error:...) for exhaustive handling; use hasError only for conditional checks alongside a separate data display:

    // ✅ Exhaustive — covers all states, preferred for full-screen states
    asyncTasks.when(
        data: (tasks) => TaskListBody(tasks: tasks),
        loading: () => const LoadingIndicator(),
        error: (e, _) => ErrorView(error: e),
    );
    
    // ✅ Conditional — show inline error banner while keeping stale data visible
    if (asyncTasks.hasError) {
        // show snackbar or inline error
    }
    final tasks = asyncTasks.valueOrNull ?? const [];
    
  3. Use safe AsyncValue accessors to prevent runtime crashes

    // ✅ Safe — returns null if state is loading or error
    final tasks = ref.watch(taskListProvider).valueOrNull;
    
    // ⚠️ Unsafe — throws StateError if state is not AsyncData
    // Only use when you have already confirmed the state is loaded
    final tasks = ref.watch(taskListProvider).requireValue;
    
  4. Use AsyncValue.guard inside notifier actions to wrap async calls

    • It catches exceptions and wraps them in AsyncError automatically
  5. Use StreamProvider for real-time data — never poll manually with Timer

  6. Always check ref.mounted after await — see Ref.mounted section above

  7. Force a provider to re-fetch with ref.invalidate

    // ✅ Invalidate from outside a notifier (e.g., after a form submit in a widget)
    ref.invalidate(taskListProvider);
    // The next watch/read will trigger a fresh build()
    
    // ✅ Invalidate from inside a notifier after a mutation
    Future<void> addTask(CreateTaskRequest request) async {
        final repo = ref.read(taskRepositoryProvider);
        await repo.createTask(request);
        if (!ref.mounted) return;
        ref.invalidateSelf(); // triggers build() to re-run and return fresh list
    }
    

    Decision: invalidateSelf() vs manual state assignment

    After a mutation:
    ├── Need optimistic UI (instant visual update before server confirms)?
    │   └── YES → Set state manually via AsyncValue.guard
    │             (e.g., remove item from list immediately, then call API)
    └── NO  → ref.invalidateSelf()  (simpler, always correct — re-runs build())
    

Error Handling in Flutter/Riverpod

Define a typed exception hierarchy using sealed classes (Dart 3+). Map infrastructure exceptions to domain exceptions inside notifier actions.

// core/errors/app_exception.dart — Typed exception hierarchy
sealed class AppException implements Exception {
    const AppException(this.message);
    final String message;

    @override
    String toString() => message;
}

class NetworkException extends AppException {
    const NetworkException(super.message, {this.statusCode});
    final int? statusCode;
}

class ValidationException extends AppException {
    const ValidationException(super.message, {required this.field});
    final String field;
}

class NotFoundException extends AppException {
    const NotFoundException(super.message);
}
// ✅ Map infrastructure exceptions to domain exceptions inside notifier actions
Future<void> addTask(CreateTaskRequest request) async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(() async {
        try {
            final repo = ref.read(taskRepositoryProvider);
            await repo.createTask(request);
            if (!ref.mounted) return state.requireValue;
            return repo.getTasks();
        } on DioException catch (e) {
            // Transform infrastructure error → domain error
            throw NetworkException(
                'Failed to create task: ${e.message}',
                statusCode: e.response?.statusCode,
            );
        }
    });
}
// ✅ Handle typed errors in UI
asyncTasks.when(
    data: (tasks) => TaskListBody(tasks: tasks),
    loading: () => const LoadingIndicator(),
    error: (error, _) => switch (error) {
        NetworkException() => ErrorView(message: 'Network error: ${error.message}'),
        NotFoundException() => const ErrorView(message: 'Not found'),
        _ => ErrorView(message: 'Unexpected error: $error'),
    },
);

Rules:

  • All custom exceptions extend AppException (sealed class)
  • Infrastructure exceptions (DioException, SocketException) are caught and re-thrown as domain exceptions
  • Never expose infrastructure types (Dio, HTTP status codes) to the UI layer
  • Use exhaustive switch on the sealed class in error display
  • See error-handling-principles.md for general error handling guidance

Navigation with go_router

go_router is the canonical navigation library.

// core/router/app_router.dart
@riverpod
GoRouter appRouter(Ref ref) {
    return GoRouter(
        initialLocation: '/tasks',
        routes: [
            GoRoute(path: '/tasks', builder: (_, __) => const TaskListView()),
            GoRoute(
                path: '/tasks/:id',
                builder: (_, state) => TaskDetailView(
                    // state.pathParameters['id'] is guaranteed non-null by the :id
                    // route pattern — acceptable use of ! in route infrastructure code
                    id: state.pathParameters['id']!,
                ),
            ),
        ],
    );
}

// Navigate — always by path, never by widget reference
context.go('/tasks/$taskId');
context.push('/tasks/new'); // push adds to the back stack

Dart Language Idioms

  1. Null safety — use ?., ??, and ??= idiomatically

    final city = user?.address?.city ?? 'Unknown';
    cache ??= await compute(); // assign only if null
    
  2. Use late only for fields initialized before first use that cannot be final

    • Prefer final fields initialized in the constructor
    • late without initialization is an unsafe nullable escape hatch
  3. Extension methods for adding behaviour to types you don't own

    extension TaskStatusLabel on TaskStatus {
        String get label => switch (this) {
            TaskStatus.pending => 'Pending',
            TaskStatus.done => 'Done',
        };
    }
    
  4. Use switch expressions (Dart 3+) for exhaustive pattern matching

    final label = status switch {
        TaskStatus.pending => 'Pending',
        TaskStatus.done => 'Done',
        // Compiler error if a case is missing
    };
    
  5. Avoid dynamic — it is the Dart equivalent of TypeScript's any


Testing

Test naming and pyramid proportions are defined in testing-strategy.md. This section covers Flutter/Riverpod 3 test patterns.

Unit Test Providers with ProviderContainer.test

ProviderContainer.test creates an isolated container that auto-disposes after the test — no manual addTearDown needed.

Shortened here. Read the whole file on GitHub.

Signals

GitHub stars
156
Forks
53
Last commit
Aug 2026
Advanced
Catalog kind
skill
Gateway key
flutter-idioms
Source
github.com/irahardianto/awesome-agv