Sub topic 8
Refreshing versus reloading: keeping previous data on screen
This chapter assumes you can write an AsyncNotifier whose build() loads data, and that you can render an AsyncValue with when or a switch. It uses the Todo, TodoRepository, todoRepositoryProvider and todosProvider from the earlier chapters. The behavior described is that of Riverpod 2.x. Section "Version notes" lists what to check if you use another major version.
Why a spinner is not always the right answer
An AsyncValue that is loading for the first time has nothing to show, so a spinner is correct. A provider that already holds a list and is loading again is a different case. If the screen swaps a visible list for a spinner every time the user pulls to refresh, the page flickers and the scroll position is lost.
Riverpod keeps the old value or error attached to the new loading state, so you can choose what to draw. This chapter covers how to tell the situations apart and how to keep the old data visible.
Three kinds of "loading"
AsyncValue has three related flags. They separate the first load from later loads, and later loads are split by what caused them.
- Initial load. There is no previous data. The state is
AsyncLoadingandhasValueisfalse. - Refresh. The provider rebuilt because you called
ref.refreshorref.invalidate, not because a dependency changed. Riverpod keeps the previous data or error and sets the loading flag on it.isRefreshingistrue. - Reload. The provider rebuilt because something it watches with
ref.watchinsidebuild()changed. The state is anAsyncLoadingthat carries the previous value.isReloadingistrue.
| Situation | Trigger | `isLoading` | `hasValue` | `isRefreshing` | `isReloading` | `when` shows (defaults) |
|---|---|---|---|---|---|---|
| Initial load | First read of the provider | true | false | false | false | `loading` |
| Refresh | `ref.refresh` or `ref.invalidate` | true | true | true | false | `data` |
| Reload | A watched dependency changed | true | true | false | true | `loading` |
| Settled | Future completed | false | true | false | false | `data` |
The last column is the part that surprises people. By default when treats a refresh as data, because the state is still an AsyncData with the loading flag set. It treats a reload as loading, because the state is an AsyncLoading. Both cases still carry the old value, and you can read it.
Reading the flags
All of these are getters on AsyncValue:
isLoadingistruein all three loading situations.hasValueistruewhen there is data, including data kept from before a refresh or reload.hasErroristruewhen there is an error. An error can also carry previous data, sohasValueandhasErrorcan both betrue.isRefreshingandisReloadingaretrueonly when there is previous data or a previous error to keep.requireValuereturns the value or throws if there is none. CheckhasValuefirst.
A common mistake is to use isLoading alone to decide whether to show a spinner. That condition is also true during a refresh when the list is already on screen, so the spinner replaces the list. Combine it with hasValue:
final showFullScreenSpinner = todos.isLoading && !todos.hasValue;
final showThinProgressBar = todos.isLoading && todos.hasValue;Keeping data visible in a widget
The widget below keeps the list on screen in every loading situation after the first one. It shows a thin progress bar while a refresh or reload is running, and it supports pull-to-refresh.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TodoListView extends ConsumerWidget {
const TodoListView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return Column(
children: [
if (todos.isLoading && todos.hasValue) const LinearProgressIndicator(),
Expanded(
child: todos.when(
skipLoadingOnReload: true,
data: (items) => RefreshIndicator(
onRefresh: () => ref.refresh(todosProvider.future),
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
for (final todo in items) ListTile(title: Text(todo.title)),
],
),
),
error: (error, stackTrace) => Center(child: Text('Failed: $error')),
loading: () => const Center(child: CircularProgressIndicator()),
),
),
],
);
}
}Three details matter here.
skipLoadingOnReload: truemakeswhencalldatafor a reload that has a previous value. Without it, a dependency change would blank the list.onRefreshreturns the future fromref.refresh(todosProvider.future).RefreshIndicatorkeeps its spinner until that future completes. Dropping thereturnwould hide the indicator at once.AlwaysScrollableScrollPhysicslets the user pull down even when the list is shorter than the screen. Without it, the gesture does nothing on short lists.
The `when` flags
AsyncValue.when takes three optional flags that decide which callback runs while previous data exists.
| Flag | Default | Effect when `true` |
|---|---|---|
| `skipLoadingOnRefresh` | `true` | A refresh with previous data calls `data` (or `error`), not `loading` |
| `skipLoadingOnReload` | `false` | A reload with previous data calls `data` (or `error`), not `loading` |
| `skipError` | `false` | If there is an error and previous data, call `data` instead of `error` |
Set skipLoadingOnRefresh: false if you want a refresh to show the full loading widget. Set skipError: true if you prefer to keep the old list visible when a refresh fails, and to show the failure some other way, such as a snackbar. Without it, a failed refresh replaces the list with the error widget even though the old data is still available.
Pattern matching and the flags
A switch expression does not apply these flags for you. The patterns match on the runtime type, so you decide what each case means.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TodoTitles extends ConsumerWidget {
const TodoTitles({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return switch (todos) {
AsyncValue(hasValue: true, :final requireValue) => Column(
children: [
if (todos.isLoading) const LinearProgressIndicator(),
for (final todo in requireValue) Text(todo.title),
],
),
AsyncError(:final error) => Text('Error: $error'),
_ => const CircularProgressIndicator(),
};
}
}The first arm tests hasValue before it reads requireValue, so it never throws. It matches initial data, a refresh and a reload alike, because all of them have a value. The cost is ordering: an error that carries previous data also matches the first arm, so the error is hidden. If you want errors to win, put the AsyncError arm first and handle the "error with old data" case there.
Triggering each state on purpose
Refresh comes from the two calls covered in the previous chapter on ref.invalidate and ref.refresh. Reload comes from a changed dependency. A small example makes the second case concrete. Here the notifier watches a filter, so changing the filter reloads the list.
import 'package:flutter_riverpod/flutter_riverpod.dart';
class FilterNotifier extends Notifier<String> {
@override
String build() => '';
void setQuery(String query) => state = query;
}
final filterProvider =
NotifierProvider<FilterNotifier, String>(FilterNotifier.new);
class FilteredTodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() async {
final query = ref.watch(filterProvider);
final all = await ref.watch(todoRepositoryProvider).fetchTodos();
return all.where((todo) => todo.title.contains(query)).toList();
}
}
final filteredTodosProvider =
AsyncNotifierProvider<FilteredTodosNotifier, List<Todo>>(
FilteredTodosNotifier.new,
);Calling ref.read(filterProvider.notifier).setQuery('ship') makes build() run again. While the new future is pending, filteredTodosProvider is an AsyncLoading with the old list attached, and isReloading is true. Calling ref.invalidate(filteredTodosProvider) runs the same build(), but this time the state is the old data flagged as loading, and isRefreshing is true. The only difference is why the rebuild happened.
In a real app the repository call would take the query as an argument. Filtering on the client keeps this example short.
Keeping data visible during your own mutations
The addTodo method from the earlier chapters assigns state = const AsyncLoading() before it saves. That is clear and correct, but whether the old list stays attached to that loading state is a detail you should not rely on without checking your version. If you want the list to stay on screen while a mutation runs, you can let a rebuild do the work instead:
Future<void> addTodo(String title) async {
await ref.read(todoRepositoryProvider).addTodo(title);
ref.invalidateSelf();
await future;
}After the write succeeds, invalidateSelf() triggers a refresh. The old list stays visible with isRefreshing set until the new list arrives. Awaiting future makes the caller wait for that reload, and it rethrows if build() fails.
This version has a trade-off. A failure in repository.addTodo is thrown to the caller and does not become an AsyncError in the state. That suits a form that shows its own error message, and it leaves the list intact. If you want the failure to appear in the provider's state, AsyncValue.guard remains the better tool. Choose based on where the error should be displayed.
Edge cases
- An error with previous data. If a refresh fails, the state is an
AsyncErrorthat still holds the old value.hasErrorandhasValueare bothtrue. CheckhasErrorfirst when you decide what to show. - A refresh that fails and then a second refresh. The second call starts from the error state.
isRefreshingistrueandhasErroristrueuntil the new future finishes, so a retry button can show progress without discarding the error message. - Nobody is listening.
ref.invalidateon a provider with no listeners does not rebuild it. The state is discarded and the next read is an initial load, with no previous data. The refresh flags only appear while a listener keeps the provider alive. autoDisposeproviders. If the last listener leaves, the provider disposes and the next listener sees an initial load. Navigating away and back is not a refresh.- Flicker from rapid changes. Typing into a search field changes the dependency on every keystroke. Each change starts a reload and abandons the previous one. Debounce the input upstream, since Riverpod does not do it for you.
Version notes
These names and defaults match Riverpod 2.x. In other major versions, check the changelog for these points before you copy code:
- The
whendefaults forskipLoadingOnRefreshandskipLoadingOnReload. - Whether
isRefreshingandisReloadingare still exposed with the same meaning. - Whether assigning
AsyncLoadingtostatekeeps the previous value. - The
valueOrNullandvaluegetters, which changed meaning between releases. This chapter avoids them for that reason and useshasValuewithrequireValue.
A short widget test that sets a filter and reads isReloading from the provider's state is the quickest way to confirm the behavior in your own project.
Exercise
A screen shows a list from an AsyncNotifier. The user changes a filter that build() watches with ref.watch. The list disappears and a full-screen spinner appears, even though the old list was available. Which flag do you set on when(), what do isReloading and isRefreshing report during that moment, and what would you add so the user still sees that something is loading?
Show answer
Set skipLoadingOnReload: true on when(). The rebuild came from a changed dependency, so the state is an AsyncLoading that carries the old value. isReloading is true and isRefreshing is false. The default for skipLoadingOnReload is false, so when() called loading. With the flag set, when() calls data with the old list. To show progress, add a thin indicator such as if (todos.isLoading && todos.hasValue) const LinearProgressIndicator() above the list.
Exercise
Why does onRefresh: () { ref.refresh(todosProvider.future); } make the RefreshIndicator disappear immediately, and how do you fix it?
Show answer
The function body uses braces and no return, so it returns null to the RefreshIndicator, which treats the refresh as finished at once. The refresh itself still runs. Return the future so the indicator waits for it: onRefresh: () => ref.refresh(todosProvider.future).