Ravi Kant Logo
Ravi Kant
Engineering HubflutterRiverpod 2.0 State Architecture

Riverpod 2.0 State Architecture

Mastering compile-safe, testable state management in Flutter applications using Notifier and AsyncNotifier.

Riverpod 2.0 State Architecture Guide

Riverpod is a reactive caching and state management framework that eliminates BuildContext dependence and guarantees compile-time safety.

Core Principles

  1. Global Provider Scope: Declare providers top-level; Riverpod handles lifetime automatically.
  2. Immutable State: Always emit new immutable copy states using copyWith().
  3. AsyncNotifier: Handle async network states cleanly with AsyncValue.
import 'package:flutter_riverpod/flutter_riverpod.dart';

@riverpod
class UserNotifier extends _$UserNotifier {
  @override
  FutureOr<User> build() async {
    return fetchUserData();
  }

  Future<void> updateName(String newName) async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      final updated = await api.updateName(newName);
      return updated;
    });
  }
}

UI Consumption

Use ConsumerWidget or ref.watch() to rebuild only when necessary:

class UserProfileWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userAsync = ref.watch(userNotifierProvider);

    return userAsync.when(
      data: (user) => Text(user.name),
      loading: () => const CircularProgressIndicator(),
      error: (err, stack) => Text('Error: $err'),
    );
  }
}