Sub topic 9
Reloading with `ref.invalidate` and `ref.refresh`
This chapter assumes you know Dart Future, async, and await, basic Flutter widgets, and Riverpod’s Provider, ref.watch, and ref.read. It also assumes that todosProvider is an AsyncNotifierProvider whose build() method loads todos.
An async provider can become stale after an action elsewhere in the application. For example, another screen might add a todo, or the user might pull down to sync with the server. Riverpod provides two related operations:
ref.invalidate(provider)marks the provider as stale.ref.refresh(provider)invalidates the provider and immediately reads it again.
Both operations cause the provider to run its build() method again when the provider is active.
Choosing between invalidation and refresh
Use invalidate when you want to request a reload but do not need the result immediately. It is useful for a reload button that only needs to start the operation.
class ReloadButton extends ConsumerWidget {
const ReloadButton({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return IconButton(
icon: const Icon(Icons.refresh),
onPressed: () {
ref.invalidate(todosProvider);
},
);
}
}The provider rebuilds, and the widgets that watch it receive the resulting states. The callback does not wait for the network request.
Use refresh when the calling code needs to await the new value. Reading .future gives a Future that completes with the provider’s next successful data value.
Future<void> reloadAndReport(WidgetRef ref) async {
final todos = await ref.refresh(todosProvider.future);
print('Reloaded ${todos.length} todos');
}ref.refresh(todosProvider.future) is effectively an invalidate followed by a read of the provider’s future. If the reload fails, the returned future throws the provider’s error, so the caller can use normal try and catch handling.
| Operation | Waits for the result | Typical use |
|---|---|---|
| `ref.invalidate(provider)` | No | Start a reload from a button |
| `ref.refresh(provider)` | Only if you await its result | Reload and use the new value |
| `ref.refresh(provider.future)` | Yes, for successful data | Reload inside an async workflow |
What happens to the displayed data?
When an AsyncNotifier already has data, Riverpod can keep that previous data while a refresh is running. This avoids replacing a useful list with a blank loading screen for every reload.
The state can contain both the previous value and a loading flag. The most useful flags are:
isLoadingmeans an asynchronous operation is currently running.isRefreshingmeans the provider was forced to recompute while it already had a value.isReloadingmeans a dependency watched bybuild()changed and caused recomputation.
The exact display behavior also depends on how the widget consumes AsyncValue. The when method generally keeps previous data visible during a refresh unless you explicitly choose to show a loading view.
class TodoStatus extends ConsumerWidget {
const TodoStatus({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(todosProvider);
if (state.isRefreshing) {
return const Text('Refreshing…');
}
return state.when(
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => Text('Could not load todos: $error'),
data: (todos) => Text('${todos.length} todos'),
);
}
}Here, the initial load shows a progress indicator. A later forced reload can still show the existing count while the separate status text says that a refresh is in progress.
Invalidation and dependency changes
Suppose build() watches a selected account provider:
@override
Future<List<Todo>> build() {
final accountId = ref.watch(selectedAccountIdProvider);
return ref.watch(todoRepositoryProvider).fetchTodos(accountId);
}When selectedAccountIdProvider changes, Riverpod automatically recomputes todosProvider. This is a dependency-driven reload, so the resulting state can report isReloading.
Call ref.invalidate(todosProvider) when the repository data changed but the watched dependencies did not. For example, after creating a todo, invalidation makes the next provider computation fetch the current server list.
Use ref.refresh(todosProvider.future) when another operation must wait until the list is current:
Future<void> addAndReload(WidgetRef ref, String title) async {
final repository = ref.read(todoRepositoryProvider);
await repository.addTodo(title);
await ref.refresh(todosProvider.future);
}This sequence prevents the caller from continuing until the add request and the subsequent list request have completed.
Exercise
Exercise
A refresh button should start reloading todos, but the button handler does not need to inspect the new list. Which operation should it call, and why?
Show answer
It should call ref.invalidate(todosProvider), because invalidation requests a rebuild without making the handler wait for the result.