Sub topic 4
Reading Other Providers with `ref`
Assume you know Dart classes, async and await, Flutter widgets, and basic Riverpod usage with ProviderScope, ConsumerWidget, and ref.watch. This chapter uses Riverpod code generation. Run the generator after changing annotated providers.
The ref parameter is the connection between a generated provider and the rest of the provider graph. It lets a provider read another provider, react to changes, register cleanup work, and observe changes for side effects.
`ref.watch`: declare a dependency
Use ref.watch when the provider's result depends on another provider. Riverpod records this relationship. If the watched provider changes, Riverpod recomputes the current provider.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'profile.g.dart';
class UserProfile {
const UserProfile(this.name);
final String name;
}
abstract class ProfileRepository {
Future<UserProfile> load();
}
class MemoryProfileRepository implements ProfileRepository {
@override
Future<UserProfile> load() async {
return const UserProfile('Ada');
}
}
@riverpod
ProfileRepository profileRepository(Ref ref) {
return MemoryProfileRepository();
}
@riverpod
Future<UserProfile> profile(Ref ref) async {
final repository = ref.watch(profileRepositoryProvider);
return repository.load();
}profile watches profileRepositoryProvider, so Riverpod knows that the repository is an input to profile. The generated profileProvider is a FutureProvider<UserProfile> because the function returns Future<UserProfile>.
Watch providers in widgets in the same way:
class ProfileName extends ConsumerWidget {
const ProfileName({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final profile = ref.watch(profileProvider);
return profile.when(
data: (user) => Text(user.name),
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => Text('Error: $error'),
);
}
}`ref.read`: take a one-time value
Use ref.read when you need a provider's current value without declaring a reactive dependency. It does not cause the current provider to recompute when that provider changes.
A command method often uses read for an action:
@riverpod
class ProfileActions extends _$ProfileActions {
@override
void build() {}
Future<void> reload() async {
final repository = ref.read(profileRepositoryProvider);
await repository.load();
ref.invalidate(profileProvider);
}
}Here, reload reads the repository only when called. It then invalidates profileProvider, which tells Riverpod to recompute it for active listeners.
Prefer watch when a value is part of the provider's result. Prefer read for an imperative action, such as calling a repository method from a button handler. Replacing watch with read merely to avoid rebuilds can create stale data.
`ref.listen`: react with a side effect
Use ref.listen when a change should trigger an action rather than become the provider's return value. The callback receives the previous value and the new value.
@riverpod
void profileLogger(Ref ref) {
ref.listen<AsyncValue<UserProfile>>(
profileProvider,
(previous, next) {
if (next.hasError) {
print('Profile loading failed: ${next.error}');
}
},
);
}Listening does not replace watching. A provider should watch a dependency when its output depends on that dependency. It should listen when it needs a side effect such as logging, analytics, or showing a notification.
In a widget, ref.listen is useful for navigation and messages:
class SaveButton extends ConsumerWidget {
const SaveButton({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.listen<AsyncValue<void>>(
saveProfileProvider,
(previous, next) {
if (next.hasError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Save failed: ${next.error}')),
);
}
},
);
return ElevatedButton(
onPressed: () => ref.read(saveProfileProvider.notifier).save(),
child: const Text('Save'),
);
}
}Cleanup with `ref.onDispose`
A provider can own resources such as timers, stream subscriptions, or controllers. Register cleanup with ref.onDispose. Riverpod calls it when the provider is destroyed, including when an auto-dispose provider loses its listeners.
@riverpod
Stream<int> ticker(Ref ref) {
final controller = StreamController<int>();
final timer = Timer.periodic(
const Duration(seconds: 1),
(_) => controller.add(DateTime.now().second),
);
ref.onDispose(() {
timer.cancel();
controller.close();
});
return controller.stream;
}This example also needs dart:async:
import 'dart:async';How the methods differ
Exercise
A generated provider loads a list from a repository. The list must refresh when the repository implementation is overridden. Which method should connect the provider to the repository, and why?
Show answer
Use ref.watch(repositoryProvider). It declares the repository as a dependency, so Riverpod can recompute the list provider when that dependency changes or is overridden.