Sub topic 8
Asynchronous data with FutureProvider and AsyncValue
This chapter assumes you know Dart futures and async/await, Flutter widget building, and the difference between ref.watch and ref.read.
Network requests and database reads do not finish immediately. A widget must represent at least three states:
- Loading: the operation is still running.
- Data: the operation succeeded.
- Error: the operation failed.
Riverpod models these states with AsyncValue. A FutureProvider runs an asynchronous function and exposes its result as an AsyncValue.
Creating a FutureProvider
The provider below simulates loading a message from a server.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final messageProvider = FutureProvider<String>((ref) async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Data loaded successfully';
});
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: MessagePage());
}
}
class MessagePage extends ConsumerWidget {
const MessagePage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final message = ref.watch(messageProvider);
return Scaffold(
appBar: AppBar(title: const Text('Messages')),
body: Center(
child: message.when(
loading: () => const CircularProgressIndicator(),
data: (value) => Text(value),
error: (error, stackTrace) => Text('Error: $error'),
),
),
);
}
}FutureProvider starts the future when something watches it. The widget receives an AsyncValue<String>, where String is the successful result type.
The when method requires handlers for loading, data, and error. This makes each state visible in the code instead of leaving an unhandled blank screen.
Errors and refresh behavior
If the future throws, Riverpod changes the provider to an error state:
final userProvider = FutureProvider<String>((ref) async {
final response = await fetchUser();
if (response.isEmpty) {
throw StateError('User was not found');
}
return response;
});A common mistake is to catch every exception inside the provider and return an empty value. That hides the difference between valid empty data and a failed request. Let meaningful errors reach AsyncValue.error, then show an appropriate message.
Another mistake is starting the future directly inside build. That can create repeated requests whenever the widget rebuilds. Put the asynchronous operation in a provider and watch it from the widget.
Exercise
What three states should a widget handle when it watches a FutureProvider?
Show answer
Loading while the future runs, data when it succeeds, and error when it fails.