Sub topic 3
Refreshing versus reloading: keeping previous data on screen
This chapter assumes you know Dart Future, async/await, Flutter widgets, and Riverpod's ref.watch and ref.read. It builds on AsyncValue and the todosProvider from the earlier chapters.
Refreshing versus reloading
A reload that shows only a spinner hides the list the user was reading. A refresh keeps the old data on screen while new data loads. To get this behavior, carry the previous value into the loading state with copyWithPrevious:
Future<void> reload() async {
state = const AsyncLoading<List<Todo>>().copyWithPrevious(state);
state = await AsyncValue.guard(
() => ref.read(todoRepositoryProvider).fetchTodos(),
);
}While the call runs, state.hasValue stays true, so the widget can still show the old items.
Reloading with ref.invalidate and ref.refresh
ref.invalidate marks a provider as stale. Its build() runs again the next time something reads the provider:
void markTodosStale(WidgetRef ref) {
ref.invalidate(todosProvider);
}ref.refresh re-runs build() immediately and returns the new value. Use it when the caller needs the result right away.
Awaiting the provider's .future
todosProvider.future gives you a Future that completes with the list. Use it when code outside a widget needs the value:
final todos = await ref.read(todosProvider.future);Testing an AsyncNotifier
Override the repository in a ProviderContainer, await the .future, and check the state:
test('reload keeps data until the new list arrives', () async {
final container = ProviderContainer(
overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
],
);
addTearDown(container.dispose);
await container.read(todosProvider.future);
await container.read(todosProvider.notifier).reload();
expect(container.read(todosProvider).requireValue, isNotEmpty);
});> Note: FakeTodoRepository is the fake repository from the testing example in the previous chapter.
Exercise
Exercise
Why does copyWithPrevious keep the list visible during a reload, when const AsyncLoading() would not?
Show answer
copyWithPrevious copies the previous AsyncData value into the loading state, so hasValue stays true. A plain AsyncLoading() carries no value, so the widget has nothing to show until the load finishes.