Sub topic 9
Reloading with ref.invalidate and ref.refresh
An AsyncNotifier loads its data once in build(). Later you will often need that load to run again: the user pulls to refresh, a save succeeds elsewhere, or the user taps "Retry" after an error. Riverpod gives you two calls for this, ref.invalidate and ref.refresh. This chapter explains what each one does, how they differ, and which one to choose.
It assumes you know AsyncValue, the when method, and how build() loads initial data. It also assumes Riverpod 2.x. The defaults described for AsyncValue.when below are the 2.x defaults, so check your own version.
Two ways to say "load again"
Both calls discard the provider's current computation and run build() again. They differ in when the rebuild happens and in what the call returns.
| Row | `ref.invalidate(provider)` | `ref.refresh(provider)` |
|---|---|---|
| Rebuild timing | Scheduled. It runs when the provider is next read, or soon after if something is listening. | Runs immediately. |
| Return value | `void` | The new state (`AsyncValue<T>`), or a `Future<T>` if you pass `provider.future`. |
| Typical use | Fire-and-forget: "this data is out of date". | You need to wait for the new data or use it. |
A useful mental model is that refresh is invalidate followed by an immediate read of the provider.
ref.invalidate: mark as stale
ref.invalidate does not compute anything itself. It tells Riverpod that the current state is no longer trustworthy. What happens next depends on whether anything is listening to the provider:
- Something is watching it (for example a
ConsumerWidget). Riverpod schedules a rebuild shortly afterwards, and the watchers see the newAsyncValue. - Nothing is watching it. The state is dropped, and
build()runs the next time someone reads the provider.
Calling invalidate several times before the rebuild happens causes only one rebuild. That makes it safe to call from several places, such as every screen that changes todos.
Two further properties are worth knowing:
- Invalidating a provider created with
.familywithout arguments invalidates every parameter combination, for exampleref.invalidate(todoProvider). Passing one argument, as intodoProvider('42'), invalidates only that instance. - Providers that depend on the invalidated provider through
ref.watchare rebuilt as well. The next section shows why.
Inside the notifier itself, use ref.invalidateSelf() to invalidate its own provider.
ref.refresh: invalidate and read now
ref.refresh forces the rebuild immediately and returns the result. What you pass decides what you get back:
ref.refresh(todosProvider)returns the newAsyncValue<List<Todo>>. Becausebuild()is asynchronous, this is normally anAsyncLoading. The data arrives later through the usual watchers.ref.refresh(todosProvider.future)returns aFuture<List<Todo>>that completes with the loaded list, or throws ifbuild()fails.
Riverpod marks the return value of refresh with an unused-result lint. If you do not need the value, use ref.invalidate. Writing ref.refresh(todosProvider); and discarding the result is the wrong tool for the job.
A runnable comparison
This example needs only flutter_riverpod and plain Dart. A counter shows how many times build() has run.
import 'package:flutter_riverpod/flutter_riverpod.dart';
var _loads = 0;
class QuoteNotifier extends AsyncNotifier<String> {
@override
Future<String> build() async {
_loads++;
final n = _loads;
await Future<void>.delayed(const Duration(milliseconds: 10));
return 'load #$n';
}
}
final quoteProvider =
AsyncNotifierProvider<QuoteNotifier, String>(QuoteNotifier.new);
Future<void> main() async {
final container = ProviderContainer();
addTearDown(container.dispose);
// Keep the provider alive, as a watching widget would.
container.listen(quoteProvider, (previous, next) {});
print(await container.read(quoteProvider.future)); // load #1
// refresh: build() starts right now and the new state is returned.
final state = container.refresh(quoteProvider);
print('loading=${state.isLoading} hasValue=${state.hasValue} '
'value=${state.value}');
print(await container.read(quoteProvider.future)); // load #2
// invalidate: nothing runs yet. The next read triggers the rebuild.
container.invalidate(quoteProvider);
print(await container.read(quoteProvider.future)); // load #3
container.dispose();
}Expected output:
load #1
loading=true hasValue=true value=load #1
load #2
load #3The second line is the key observation. Right after refresh, the state is loading, but it still carries the previous value load #1. The next sections explain why.
How the calls flow
What the user sees while it reloads
A reload does not have to flash a spinner. When build() runs again for a provider that already has data, Riverpod does not start from an empty AsyncLoading. It creates an AsyncLoading that carries the previous data or error. That is why hasValue was true in the example above.
AsyncValue.when decides whether to show the old data or the loading branch. It has three flags:
| Flag | Default | Meaning |
|---|---|---|
| `skipLoadingOnRefresh` | `true` | If the rebuild came from `ref.refresh` or `ref.invalidate`, keep showing the previous data or error instead of calling `loading`. |
| `skipLoadingOnReload` | `false` | If the rebuild came from a changed `ref.watch` dependency, call `loading` even though previous data exists. |
| `skipError` | `false` | While loading with a previous error, call `loading` rather than `error`. (The flag also affects how an error with previous data is shown.) |
Riverpod's vocabulary has two words for this. A refresh is a rebuild that nothing upstream caused, because your code called invalidate or refresh. A reload is a rebuild caused by a dependency change. The defaults mean a pull-to-refresh keeps the list on screen, while a change of a watched filter shows the spinner.
You can change this per call. Use skipLoadingOnReload: true to keep data visible on filter changes too. If you want an invalidation to count as a reload so skipLoadingOnReload governs it, pass asReload: true:
import 'package:flutter_riverpod/flutter_riverpod.dart';
void reloadWithSpinner(WidgetRef ref) {
ref.invalidate(todosProvider, asReload: true);
}The isRefreshing and isReloading getters on AsyncValue let you build custom indicators, such as a thin progress bar above the list while the data stays visible.
Pull to refresh with ref.refresh
RefreshIndicator shows its spinner until the Future returned from onRefresh completes. That is the case for ref.refresh(provider.future), because it completes exactly when the new data is ready. It assumes the todosProvider from the earlier chapters.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class RefreshableTodoList extends ConsumerWidget {
const RefreshableTodoList({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return RefreshIndicator(
onRefresh: () async {
try {
await ref.refresh(todosProvider.future);
} catch (_) {
// The error is already in the provider state. The list below
// shows it, so the indicator can simply close.
}
},
child: todos.when(
data: (items) => ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
for (final todo in items) ListTile(title: Text(todo.title)),
],
),
error: (error, stackTrace) => ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [Center(child: Text('Failed: $error'))],
),
loading: () => const Center(child: CircularProgressIndicator()),
),
);
}
}Three details are easy to miss:
- The
try/catchis deliberate. Ifbuild()throws, the future fromrefreshthrows too. The same error also becomes the provider'sAsyncErrorstate, so the widget shows it without help. - The
AlwaysScrollableScrollPhysicslets the user pull down even when the list is short or the content is an error message. - During the refresh,
whenkeeps showing the old list, becauseskipLoadingOnRefreshdefaults totrue. TheRefreshIndicatorsupplies the progress feedback.
Retry buttons with ref.invalidate
A retry button does not need a result. It only needs the provider to try again, and the error branch of when will show whatever comes next.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TodoErrorView extends ConsumerWidget {
const TodoErrorView({super.key, required this.error});
final Object error;
@override
Widget build(BuildContext context, WidgetRef ref) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Failed: $error'),
FilledButton(
onPressed: () => ref.invalidate(todosProvider),
child: const Text('Retry'),
),
],
);
}
}This is the idiomatic use of invalidate: the caller does not wait, and the UI follows the provider.
Invalidate after a mutation
In an earlier chapter, addTodo set state = const AsyncLoading() and then used AsyncValue.guard to write the result. That is explicit, but a plain AsyncLoading() throws away the old list, so the screen shows a spinner during every save.
An alternative is to perform the write and then let the provider reload itself:
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchTodos();
}
Future<void> addTodo(String title) async {
final repository = ref.read(todoRepositoryProvider);
await repository.addTodo(title);
ref.invalidateSelf();
await future;
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);Here the list stays visible while the new fetch runs. await future makes the returned Future complete only when the reload is done, so a caller can show a "saving" indicator for the full duration. The trade-off is that a failed write throws out of addTodo instead of landing in the state, so the caller needs a try/catch. AsyncValue.guard keeps errors inside the state and needs no try/catch. Choose based on where you want errors to appear.
Choosing between the two
- Need the new data in your code, or need to wait until it is loaded (pull to refresh, "save, then navigate")? Use
await ref.refresh(provider.future). - Only need the UI to catch up (retry button, "something changed elsewhere")? Use
ref.invalidate(provider). - Are you inside the notifier? Use
ref.invalidateSelf(), plusawait futureif you need to wait. - Do you want to reload every instance of a family? Use
ref.invalidate(familyProvider)with no argument.
Common errors
- Discarding the result of
ref.refresh. The analyzer warns about it. Switch toref.invalidate, or use the result. - Calling either method inside
build()of a widget. Rebuilding a provider while a widget builds causes loops or assertion errors. Call them from callbacks such asonPressed, or from listeners. - Expecting
invalidateto run synchronously. Code on the next line still sees the old state. If you need the new data, userefreshor readprovider.future. - Expecting a reload to keep data on screen with
when's defaults. Dependency-triggered reloads show the loading branch unless you setskipLoadingOnReload: true. - Refreshing a provider that has no listeners and is
autoDispose. The state may already be disposed. A refresh then simply starts a fresh load, and nothing is lost, but there is no previous data to show.
Exercise
A screen shows a todo list and has a Retry button in its error view. The button currently calls ref.refresh(todosProvider); and the analyzer reports an unused result. What should the button call instead, and why? Also, a pull-to-refresh handler needs to keep its spinner visible until the new list has arrived. Which call does it use?
Show answer
The Retry button should call ref.invalidate(todosProvider). It does not use the returned value, and the error branch of when shows whatever state follows. The pull-to-refresh handler should await ref.refresh(todosProvider.future), because that future completes only when build() has finished loading, so the RefreshIndicator stays open for exactly that long.