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
- Global Provider Scope: Declare providers top-level; Riverpod handles lifetime automatically.
- Immutable State: Always emit new immutable copy states using
copyWith(). - 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'),
);
}
}