Sub topic 10
Awaiting the provider's .future
This chapter assumes you can read an AsyncNotifier and its build() method, and you know what AsyncValue holds. You also need await and try/catch in Dart. The chapter covers .future, the handle that lets you await an async provider. It explains when to use it instead of the AsyncValue, and the mistakes that cause trouble.
Two views of the same provider
An AsyncNotifierProvider exposes its result in two forms:
todosProvideris theAsyncValue<List<Todo>>. It is a snapshot (loading, data or error) that you can render right away.todosProvider.futureis aFuture<List<Todo>>. It completes when the provider has a settled value, so you canawaitit.
The AsyncValue suits widgets because a widget must draw something on every frame. It cannot wait. Plain Dart code in a provider, a callback or a test is different. That code often wants to say "give me the list once it is loaded" and then continue. The .future handle does that without a switch over three states.
| Expression | Type | Typical use |
|---|---|---|
| `ref.watch(todosProvider)` | `AsyncValue<List<Todo>>` | Render loading, data and error in a widget |
| `ref.watch(todosProvider.future)` | `Future<List<Todo>>` | Depend on the result inside another provider's build |
| `ref.read(todosProvider.future)` | `Future<List<Todo>>` | Wait for the result inside a callback or a test |
| `ref.watch(todosProvider.selectAsync(...))` | `Future<R>` | Depend on one derived part of the result |
| `ref.refresh(todosProvider.future)` | `Future<List<Todo>>` | Reload now and wait for the new result |
Setup used in this chapter
The examples use the todo model from earlier chapters. This listing puts it in one file, with one extra method that uses the notifier's own future.
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Todo {
const Todo(this.id, this.title);
final String id;
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> addTodo(String title);
}
final todoRepositoryProvider = Provider<TodoRepository>((ref) {
throw UnimplementedError('Override with a real repository');
});
class TodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchTodos();
}
Future<void> addIfMissing(String title) async {
// Wait for the initial load before deciding anything.
final current = await future;
if (current.any((todo) => todo.title == title)) return;
final repository = ref.read(todoRepositoryProvider);
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
await repository.addTodo(title);
return repository.fetchTodos();
});
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);Inside the notifier, future is a getter on the AsyncNotifier class. It is the same future that todosProvider.future gives you from outside.
What the future does
The future follows the provider's state:
- While
build()is running, the future is pending. - When
build()returns a value, the future completes with it. - When
build()throws, the future completes with that error.awaitrethrows it, so you can catch it withtry/catch. - If the provider already has data, the future completes right away with that data.
The future also follows later changes. When the notifier sets state = const AsyncLoading(), a future read at that moment stays pending. It completes when the state next settles into data or an error. So a caller that awaits during a mutation gets the result of the mutation, not the stale list.
Depending on async data in another provider
The most common use of .future is a provider that needs the loaded value of another one. Watch the future, then await it:
import 'package:flutter_riverpod/flutter_riverpod.dart';
final todoCountProvider = FutureProvider<int>((ref) async {
final todos = await ref.watch(todosProvider.future);
return todos.length;
});Two things happen here. The ref.watch call registers a dependency, so todoCountProvider rebuilds whenever todosProvider produces a new value. The await means the code after it only sees real data. If todosProvider fails, todoCountProvider fails with the same error and its own AsyncValue shows AsyncError.
Compare this with watching the AsyncValue:
final todoCountFromValueProvider = Provider<int?>((ref) {
final todos = ref.watch(todosProvider);
return todos.valueOrNull?.length;
});This version never waits and never throws. It returns null while loading and also on error, so the caller cannot tell those cases apart. Use the AsyncValue form when null is a fine answer. Use the .future form when you want to keep the loading and error semantics as an AsyncValue of the result.
Selecting a part with selectAsync
If you only need one derived value, selectAsync limits rebuilds. The provider rebuilds only when the selected value changes:
import 'package:flutter_riverpod/flutter_riverpod.dart';
final hasTodosProvider = FutureProvider<bool>((ref) async {
final count = await ref.watch(
todosProvider.selectAsync((todos) => todos.length),
);
return count > 0;
});When a todo is added and the list goes from 3 items to 4, hasTodosProvider is not recomputed in a way that changes its answer, because count > 0 only needs the selected length to differ. Without selectAsync, any new list would trigger a rebuild even when the result is identical.
Awaiting in callbacks with ref.read
Event handlers run once, so they use ref.read, not ref.watch. This is the same rule as for synchronous providers. A handler that needs the loaded list reads the future and awaits it:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class ExportButton extends ConsumerWidget {
const ExportButton({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return TextButton(
onPressed: () async {
final messenger = ScaffoldMessenger.of(context);
try {
final todos = await ref.read(todosProvider.future);
messenger.showSnackBar(
SnackBar(content: Text('Exported ${todos.length} todos')),
);
} catch (error) {
messenger.showSnackBar(
SnackBar(content: Text('Export failed: $error')),
);
}
},
child: const Text('Export'),
);
}
}The try/catch is needed because a failed provider makes await throw. The code takes the ScaffoldMessenger before the await. Using context after an async gap is the usual source of the "use of BuildContext across async gaps" lint.
Awaiting a reload
Chapter 9 introduced ref.refresh. The .future form of it returns a Future that completes when the reload finishes. This is exactly what RefreshIndicator wants, because it keeps the spinner visible until its onRefresh future completes:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class RefreshableTodos extends ConsumerWidget {
const RefreshableTodos({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return RefreshIndicator(
onRefresh: () => ref.refresh(todosProvider.future),
child: ListView(
children: [
for (final todo in todos.valueOrNull ?? const <Todo>[])
ListTile(title: Text(todo.title)),
],
),
);
}
}The widget still watches the AsyncValue for drawing. The refresh uses the future only to know when to stop the spinner. If the reload throws, the onRefresh future completes with an error, and Flutter reports it as an unhandled error unless you catch it. Wrap the call in a function with try/catch if you want to show a message instead.
ref.invalidate returns nothing, so there is no future to await. If you invalidate and then need to wait, read the future afterwards:
Future<int> reloadAndCount(WidgetRef ref) async {
ref.invalidate(todosProvider);
final todos = await ref.read(todosProvider.future);
return todos.length;
}Reading the future after invalidate is what starts the rebuild, so the await waits for fresh data. This does the same job as ref.refresh(todosProvider.future), which is shorter and also makes the intent clear.
Waiting for the initial load inside the notifier
A notifier method can run before build() has finished. A user tap on "add" could arrive while the first load is still in flight. At that moment state is AsyncLoading, and state.value is null. The addIfMissing method from the setup avoids this by awaiting future first.
The alternative, state.requireValue, throws if the state has no value yet. Use it only when you know loading is finished, for example in a method that the UI can call only from the data branch of when.
Common mistakes
Using ref.watch(provider.future) in a callback
ref.watch in an event handler subscribes for the lifetime of the provider and is flagged by Riverpod as a misuse. Use ref.read in handlers and ref.watch only during build.
Forgetting that await can throw
A future from a failed provider completes with an error. Without try/catch, the exception surfaces in a button handler as an unhandled error. If the caller is itself a provider, the error is fine, because it becomes the AsyncError of that provider.
Reading the future of an auto-disposed provider with no listener
If a provider is auto-disposed and nothing is listening, it can be disposed while your await is pending. Then you may see an error that the provider was disposed during loading. Two fixes work. Keep the provider alive with ref.keepAlive(), or hold a listener open with ref.watch in a provider's build for as long as you need the result. Use ref.read(...future) in a handler only for providers that a widget is already watching.
Treating the future as a snapshot
A Future you stored in a variable is the future at that moment. After a later reload, the provider has a new future and your stored one still holds the old result. Do not keep it in a field. Ask the provider again each time.
Using .future in a build method to render
Passing ref.watch(todosProvider.future) to a FutureBuilder works, but it throws away what AsyncValue gives you: isRefreshing, previous data during reloads, and when. Render from the AsyncValue.
Testing with the future
In tests, .future is how you wait for the initial load without polling:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class StubRepository implements TodoRepository {
@override
Future<List<Todo>> fetchTodos() async => const [Todo('1', 'First')];
@override
Future<void> addTodo(String title) async {}
}
void main() {
test('todoCountProvider waits for the list', () async {
final container = ProviderContainer(
overrides: [
todoRepositoryProvider.overrideWithValue(StubRepository()),
],
);
addTearDown(container.dispose);
final count = await container.read(todoCountProvider.future);
expect(count, 1);
});
}The test reads todoCountProvider.future. That starts todoCountProvider, which in turn starts todosProvider and the stub repository. The test then waits for the whole chain. There is no pumpAndSettle and no manual delay.
Choosing between value and future
| Question | Use |
|---|---|
| Am I drawing UI that must show loading and error? | The `AsyncValue` with `when` or a `switch` |
| Am I writing a provider that needs loaded data? | `await ref.watch(p.future)` |
| Do I need only one derived field? | `ref.watch(p.selectAsync(...))` |
| Am I in a tap handler or a test? | `await ref.read(p.future)` |
| Do I need to wait for a reload to end? | `await ref.refresh(p.future)` |
Exercise
A FutureProvider<int> called totalProvider needs the length of the todo list. A teammate writes final todos = ref.watch(todosProvider).value!; inside it. What goes wrong on the first run, and how do you fix it?
Show answer
On the first run the provider is still loading, so value is null and the ! throws a null-check error. If the provider failed, value is also unusable. Fix it by awaiting the future: final todos = await ref.watch(todosProvider.future);. The await waits for the load, rethrows a load error as the error of totalProvider, and the watch keeps the dependency so the total updates when the list changes.
Exercise
A RefreshIndicator should keep spinning until the todo list reloads. Which line goes in onRefresh, and why does ref.invalidate(todosProvider) not work there?
Show answer
Use onRefresh: () => ref.refresh(todosProvider.future). It starts the reload at once and returns a future that completes when the new data or error arrives, so the spinner stops at the right time. ref.invalidate returns void. It only marks the provider stale, so there is no future for onRefresh to wait on and the spinner would stop immediately.