Sub topic 3
Limiting rebuilds with select
This chapter assumes you know Dart async/await, Flutter widgets, and the basics of ProviderScope, ConsumerWidget, and Notifier from earlier chapters.
Limiting rebuilds with select
Watching a whole object rebuilds the widget on any change to that object. select watches one field and rebuilds only when that field changes.
class NameLabel extends ConsumerWidget {
const NameLabel({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final name = ref.watch(profileProvider.select((p) => p.name));
return Text(name);
}
}Reacting to changes with ref.listen
ref.listen runs a callback when a provider changes. It does not rebuild the widget, so it suits side effects such as showing a snackbar.
ref.listen<AsyncValue<List<Todo>>>(todoListProvider, (previous, next) {
if (next.hasError && !next.isLoading) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Could not load todos')),
);
}
});Parameterized providers with family
A family creates one provider state per argument. autoDispose frees a state once no widget listens to it.
final userNameProvider =
FutureProvider.autoDispose.family<String, int>((ref, id) async {
return 'User $id';
});
// In a widget: final name = ref.watch(userNameProvider(42));Structuring an app around repositories and providers
Put data access behind an abstract repository. A provider exposes it, and tests or other environments override that provider.
abstract class TodoRepository {
Future<List<Todo>> fetchAll();
}
final todoRepositoryProvider = Provider<TodoRepository>(
(ref) => throw UnimplementedError('Override todoRepositoryProvider'),
);Testing providers with ProviderContainer and overrides
A ProviderContainer runs providers without widgets. overrideWithValue swaps in a fake repository.
test('todo list loads from the repository', () async {
final container = ProviderContainer(overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
]);
addTearDown(container.dispose);
final todos = await container.read(todoListProvider.future);
expect(todos.single.title, 'Write tests');
});Common mistakes and best practices
| Mistake | Fix |
|---|---|
| Calling `ref.watch` inside a button callback | Use `ref.read` in callbacks |
| Watching a whole object when one field matters | Use `select` |
| Using `ref.watch` for side effects | Use `ref.listen` |
A look at code generation with riverpod_generator
The riverpod_generator package writes provider declarations for you. You annotate a function with @riverpod, then run dart run build_runner build. The annotated function counter produces counterProvider.
@riverpod
int counter(Ref ref) => 0;Exercise
A widget watches profileProvider.select((p) => p.name). The user's age changes. Does the widget rebuild?
Show answer
No. The select returns only the name, and the name has not changed, so the widget is skipped.