Sub topic 8
Asynchronous data with FutureProvider and AsyncValue
This chapter assumes you can write Dart async functions, that you have used ProviderScope and ConsumerWidget, and that you know the difference between ref.watch and ref.read. It also assumes you have seen a synchronous Provider. Here you will load data that arrives later and show it safely in a widget.
The problem with values that arrive later
A network call, a database query, or a file read returns a Future. A widget's build method must return a widget immediately, so it cannot wait. With plain Flutter you usually solve this with a FutureBuilder or with fields such as isLoading and error that you keep in sync by hand.
Riverpod solves this with two pieces:
FutureProvider<T>runs an async function and exposes its result.AsyncValue<T>is the value a widget actually receives. It is one object that says whether the data is loading, loaded, or failed.
A widget never sees a Future. It sees an AsyncValue, which is always available right away.
Declaring a FutureProvider
A FutureProvider takes a function that returns a Future. Riverpod calls it the first time someone listens and caches the outcome. Every other listener shares that one result, so the request runs once.
The example below is a complete app. The repository is a fake that waits half a second, so you can run it without a server.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Weather {
const Weather(this.city, this.celsius);
final String city;
final int celsius;
}
class WeatherRepository {
Future<Weather> fetch(String city) async {
await Future<void>.delayed(const Duration(milliseconds: 500));
return Weather(city, 12);
}
}
final weatherRepositoryProvider =
Provider<WeatherRepository>((ref) => WeatherRepository());
final weatherProvider = FutureProvider<Weather>((ref) async {
final repository = ref.watch(weatherRepositoryProvider);
return repository.fetch('Oslo');
});
void main() {
runApp(const ProviderScope(child: MaterialApp(home: WeatherPage())));
}
class WeatherPage extends ConsumerWidget {
const WeatherPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final weather = ref.watch(weatherProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Weather'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: () => ref.invalidate(weatherProvider),
),
],
),
body: Center(
child: weather.when(
data: (w) => Text('${w.city}: ${w.celsius} °C'),
error: (error, stackTrace) => Text('Failed: $error'),
loading: () => const CircularProgressIndicator(),
),
),
);
}
}Three things happen here:
weatherProviderwatchesweatherRepositoryProvider, so it depends on another provider. This is the same composition idea you saw with synchronous providers.- The widget watches the provider and gets an
AsyncValue<Weather>. whenpicks a widget for each state.
The three states of AsyncValue
AsyncValue<T> has three subtypes. Exactly one describes the current state.
| State | Meaning | Typical content |
|---|---|---|
| `AsyncLoading` | The future has not finished. | Spinner or skeleton |
| `AsyncData` | The future completed with a value. | The loaded value |
| `AsyncError` | The future threw. | Error and stack trace |
The state moves between them as the provider runs and re-runs.
An exception inside the provider function does not crash the widget. Riverpod catches it and stores it as an AsyncError. Your widget sees the error as a normal state and decides how to show it.
Handling every state with when
when takes three callbacks, and all three are required. If you forget the error case the code does not compile. The compiler pushes you to handle failure instead of leaving it to chance.
Useful properties and methods on AsyncValue:
isLoading,hasValue, andhasErrorare boolean checks.maybeWhenlets you handle some states and supply anorElsefallback for the rest.whenDatamaps only the data case and keeps loading and error as they are.requireValuereturns the value or throws if there is none. Use it only where you know data exists.
If you want one callback for the data case and a default for everything else, use maybeWhen:
final label = ref.watch(weatherProvider).maybeWhen(
data: (w) => '${w.celsius} °C',
orElse: () => '...',
);Refreshing: invalidate versus refresh
A FutureProvider caches its result. To run it again, you have two options.
ref.invalidate(provider)marks the cached state as stale. The provider re-runs the next time something needs it. If a widget is already listening, that happens right away. It returns nothing.ref.refresh(provider)invalidates the provider and immediately returns the new state. Use it when you need the new value in the same expression.
// Just trigger a reload from a button:
onPressed: () => ref.invalidate(weatherProvider),
// Reload and wait for the result:
final fresh = await ref.refresh(weatherProvider.future);Both calls belong in callbacks, not directly in build. Calling invalidate during build would schedule another rebuild each time, which is a loop.
What the UI shows while reloading
When a provider that already has data reloads, Riverpod does not throw the old data away. The new AsyncLoading carries the previous value or error. By default, when keeps showing the previous data during an explicit refresh through invalidate or refresh. It shows the loading widget only for the first load.
To react to reloading yourself, check isRefreshing or isLoading alongside hasValue:
final weather = ref.watch(weatherProvider);
final stale = weather.isLoading && weather.hasValue;You can then show the old data with a thin progress bar on top. This usually feels better than a full-screen spinner.
The exact defaults of skipLoadingOnRefresh and skipLoadingOnReload have changed between Riverpod versions. Check the documentation for the version in your pubspec.yaml before you depend on them.
Using the future directly
Sometimes you need the Future itself, for example inside another provider that must wait for the first one. Read it with .future:
final summaryProvider = FutureProvider<String>((ref) async {
final weather = await ref.watch(weatherProvider.future);
return '${weather.city} is ${weather.celsius} °C';
});summaryProvider stays in AsyncLoading until weatherProvider finishes. If weatherProvider fails, the error carries over to summaryProvider. Each provider keeps a single, simple async function.
Common mistakes
- Treating
AsyncValuelike the data.weather.celsiusdoes not compile. You must go throughwhenor checkhasValuefirst. - Swallowing errors. Writing only a loading and data branch with
maybeWhencan hide failures behind anorElsespinner. Show the error somewhere. - Catching exceptions in the provider and returning a fake value. This hides the failure from the UI. Let the exception escape and show it through
AsyncError. - Doing work that changes data in a FutureProvider. It is meant for reading. Writes belong in an
AsyncNotifier, which the next chapter covers.
Testing a FutureProvider
You can test the provider without any widgets. Create a ProviderContainer, override the repository, and wait on .future:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class FakeWeatherRepository extends WeatherRepository {
@override
Future<Weather> fetch(String city) async => Weather(city, 20);
}
void main() {
test('weatherProvider returns data from the repository', () async {
final container = ProviderContainer(overrides: [
weatherRepositoryProvider.overrideWithValue(FakeWeatherRepository()),
]);
addTearDown(container.dispose);
final weather = await container.read(weatherProvider.future);
expect(weather.celsius, 20);
});
}The test uses the classes from the first example. container.read(weatherProvider.future) waits for the result, so no sleeping or polling is needed.
When to choose FutureProvider
Use FutureProvider when the data is read-only and comes from one async call. Typical cases are loading a profile, a settings file, or a list that the user only views and refreshes. If the user can also change the data, such as adding or deleting items, move to AsyncNotifier. It has the same AsyncValue output, plus methods that change state.
Exercise
A screen watches a FutureProvider. The user taps "Refresh", which calls ref.invalidate. You want the old data to stay visible with a small progress indicator instead of being replaced by a full-screen spinner. Which properties of AsyncValue do you check, and what do you show?
Show answer
Check that isLoading is true and hasValue is true at the same time. That means a reload is running and the previous data is still available. Show the previous data (for example through the value in the data callback, or by reading the value directly) and add a small progress indicator on top. Show the full-screen spinner only when isLoading is true and hasValue is false, which is the first load.
Exercise
Why is final w = ref.watch(weatherProvider); Text(w.value.celsius) a bad way to display the weather, even if it compiles in your Riverpod version?
Show answer
The value can be missing while the provider is loading or after an error, so the code can fail at runtime with a null error or by throwing the stored error. Use when (or check hasValue) so each state gets its own widget.