Sub topic 10
Awaiting the Provider's `.future`
This chapter assumes that you know Future, async, and await, and that todosProvider is an AsyncNotifierProvider<TodosNotifier, List<Todo>> from the previous chapter.
An AsyncValue<List<Todo>> is useful when a widget must render loading, data, or error states. Sometimes, however, other code only needs to wait until the provider finishes loading. The .future property exposes that operation as a Future<List<Todo>>.
What `.future` represents
For an asynchronous provider, .future converts the provider's current asynchronous state into a Dart Future.
- If the provider is loading, the future waits.
- If the provider finishes with data, the future completes with that data.
- If the provider finishes with an error, awaiting the future throws that error.
The future resolves when build() completes. It does not remove the provider's normal state. Widgets can still watch todosProvider and receive an AsyncValue.
Awaiting initial data
Use .future when a callback must perform work after the initial load. For example, a screen might wait for todos before selecting the first item.
Future<Todo?> loadFirstTodo(WidgetRef ref) async {
try {
final todos = await ref.read(todosProvider.future);
if (todos.isEmpty) {
return null;
}
return todos.first;
} catch (error, stackTrace) {
debugPrint('Could not load todos: $error');
debugPrintStack(stackTrace: stackTrace);
return null;
}
}ref.read is appropriate in this callback because the callback needs one result. It does not need to rebuild when the provider changes. If the callback must react to dependency changes, use ref.watch inside another provider's build or factory function.
Awaiting .future does not return an AsyncValue. The result is the actual value, such as List<Todo>. This differs from reading the provider directly:
final state = ref.read(todosProvider); // AsyncValue<List<Todo>>
final todos = await ref.read(todosProvider.future); // List<Todo>Since errors are thrown by the future, use try and catch when the caller needs to handle failure. Do not expect to inspect state.error after awaiting .future.
Using `.future` between providers
A provider can await another asynchronous provider to create a dependency. This is useful when one result depends on another result.
final todoCountProvider = FutureProvider<int>((ref) async {
final todos = await ref.watch(todosProvider.future);
return todos.length;
});Here, todoCountProvider waits for todosProvider. Because it uses ref.watch, Riverpod tracks the dependency. When todosProvider is rebuilt, the count provider can run again.
A widget still needs to handle the count provider's states:
class TodoCount extends ConsumerWidget {
const TodoCount({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(todoCountProvider);
return count.when(
data: (value) => Text('$value todos'),
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => Text('Error: $error'),
);
}
}Use .future for asynchronous control flow. Use the provider itself when a widget must display state.
Awaiting a reload
You can combine .future with ref.refresh when an action must start a new load and wait for its result.
Future<List<Todo>> reloadTodos(WidgetRef ref) {
return ref.refresh(todosProvider.future);
}This call invalidates the current result, starts the provider again, and returns a future for the new result. A caller can await it and catch errors:
Future<void> refreshAndLog(WidgetRef ref) async {
try {
final todos = await ref.refresh(todosProvider.future);
debugPrint('Reloaded ${todos.length} todos');
} catch (error) {
debugPrint('Reload failed: $error');
}
}Do not confuse this with ref.invalidate(todosProvider). Invalidation marks the provider stale, but it does not give the caller a future to await. Choose refresh when the caller needs the new value immediately. Choose invalidate when another read can trigger the rebuild later.
Testing with `.future`
Tests can await the provider without listening to widget output. This makes .future convenient for testing initial loads.
test('loads the initial todos', () async {
final container = ProviderContainer(
overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
],
);
addTearDown(container.dispose);
final todos = await container.read(todosProvider.future);
expect(todos, hasLength(1));
expect(todos.first.title, 'Write tests');
});If the fake repository throws, the await expression throws too. Test that behavior with expectLater and a future matcher, or use try and catch when you need to inspect the error.
Exercise
What is the difference between ref.read(todosProvider) and await ref.read(todosProvider.future)?
Show answer
The first returns an AsyncValue<List<Todo>>, which includes loading, data, or error state. The second waits for completion and returns List<Todo> or throws if loading fails.