Sub topic 2
ref.watch versus ref.read
This chapter assumes you know Dart classes, generics, and async/await. You should also know Flutter's build method and have seen setState. Your app root wraps the widget tree in a ProviderScope.
ref.watch and ref.read
ref.watch(provider) subscribes a widget to a provider. When the value changes, Riverpod rebuilds the widget. Call watch inside build.
ref.read(provider) returns the current value once and does not subscribe. Call read in event handlers such as onPressed.
The rule: watch in build, read in callbacks.
Mutable state with Notifier and NotifierProvider
A Notifier<T> holds a value of type T in state. Its build method returns the initial state. Widgets change state by calling a method on the notifier, not by assigning state directly.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final counterProvider = NotifierProvider<Counter, int>(Counter.new);
class CounterPage extends ConsumerWidget {
const CounterPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Scaffold(
body: Center(child: Text('$count')),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).increment(),
child: const Icon(Icons.add),
),
);
}
}
void main() => runApp(
const ProviderScope(child: MaterialApp(home: CounterPage())),
);Deriving state by composing providers
A provider can watch another provider. The derived provider recomputes only when its source changes.
final isEvenProvider = Provider<bool>((ref) {
return ref.watch(counterProvider).isEven;
});Asynchronous data with FutureProvider and AsyncValue
FutureProvider<T> wraps a Future<T>. Its value is an AsyncValue<T>, which is in one of three states: loading, data, or error. Use when to handle all three, so the widget cannot forget one.
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return todos.when(
data: (items) => Text('${items.length} items'),
error: (error, stackTrace) => Text('Error: $error'),
loading: () => const CircularProgressIndicator(),
);
}Loading, updating and refreshing with AsyncNotifier
An AsyncNotifier returns a Future from build. Its state is an AsyncValue. The example below loads a list, adds an item, and reloads the list.
class Todos extends AsyncNotifier<List<String>> {
@override
Future<List<String>> build() async {
await Future<void>.delayed(const Duration(seconds: 1));
return ['Buy milk'];
}
Future<void> add(String title) async {
final items = await future;
state = AsyncData([...items, title]);
}
Future<void> reload() async {
ref.invalidateSelf();
}
}
final todosProvider =
AsyncNotifierProvider<Todos, List<String>>(Todos.new);| Call | Subscribes? | Typical location |
|---|---|---|
| ref.watch | Yes | build |
| ref.read | No | onPressed and other callbacks |
Exercise
In the Todos notifier, why does add use await future before setting state?
Show answer
future is the Future from build. Awaiting it makes sure the initial list has loaded, so add appends to real data instead of an empty or loading state.
Exercise
Which call should a button's onPressed use to add a todo, ref.watch or ref.read?
Show answer
ref.read(todosProvider.notifier).add(title). The callback runs once per tap and must not subscribe.