CodeBlanks Logo Icon CodeBlanks

FutureProvider

Provide async data with FutureProvider.

What is FutureProvider?

FutureProvider wraps a function that returns a Future and exposes its result automatically as an AsyncValue. When the future completes it switches to AsyncValue.data, on error to AsyncValue.error, and while waiting to AsyncValue.loading. You do not manage the states by hand.

final userProvider = FutureProvider<String>((ref) async {
  await Future.delayed(Duration(seconds: 1));
  return 'Ayşe';
});

Watching a FutureProvider

ref.watch(futureProvider) returns an AsyncValue<T>, not a T directly. You use the when method to turn loading, data and error states into different widgets. This pattern is standard on screens that call an API.

final asyncValue = ref.watch(userProvider);
return asyncValue.when(
  data: (name) => Text(name),
  loading: () => CircularProgressIndicator(),
  error: (e, s) => Text('Error: $e'),
);

Practice Define and read a FutureProvider

Define a FutureProvider<String> named userProvider whose create function is async and returns 'Ayşe'. In main, use a ProviderContainer to await userProvider.future and print it.

Starter code

main.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';

// userProvider adında FutureProvider tanımla
// oluşturucu fonksiyon async, 'Ayşe' döndürsün

void main() async {
  // ProviderContainer ile userProvider.future'ı bekle ve yazdır
}

Sample solution

main.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';

final userProvider = FutureProvider<String>((ref) async {
  return 'Ayşe';
});

void main() async {
  final container = ProviderContainer();
  final value = await container.read(userProvider.future);
  print(value);
}

Expected output

Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What should the create function of a FutureProvider return?

  • Widget
  • AsyncValue<T>
  • Future<T> Correct answer
  • Stream<T>

Explanation: The async function of a FutureProvider returns a Future<T>; Riverpod wraps the result into an AsyncValue itself.

2 Define a FutureProvider

Question
final userProvider = ____<String>((ref) async {
  return 'Ayşe';
});
Answer
final userProvider = FutureProvider<String>((ref) async {
  return 'Ayşe';
});

Explanation: FutureProvider is the provider used to wrap functions that return a Future.

3 FutureProvider parts

Term Meaning
FutureProvider Provides a Future result
ref.watch(provider) Returns an AsyncValue
async (ref) => The create function
when Handles the states

All lessons in Advanced