What are the basic different provider types in Riverpod, such as Provider, StateProvider, and FutureProvider, and when would you specifically reach for each individual different one?
Short answer
Riverpod offers several genuinely distinct provider types each suited to a different specific particular use case, with the basic Provider type used for exposing a genuinely simple computed value or a service instance that itself never actually changes, StateProvider used for…
Advertisement
AModel answer
Riverpod offers several genuinely distinct provider types each suited to a different specific particular use case, with the basic Provider type used for exposing a genuinely simple computed value or a service instance that itself never actually changes, StateProvider used for holding a genuinely simple piece of mutable state such as a basic counter or a currently selected filter value, and FutureProvider used specifically for properly exposing the eventual result of an asynchronous operation, such as a network request, while conveniently and automatically handling its loading and error states entirely for you.
final userProvider = FutureProvider<User>((ref) async {
return await apiClient.fetchCurrentUser();
});Real-world example
A profile screen uses a FutureProvider specifically to fetch the current user's own profile data, automatically and conveniently receiving proper built in loading and error state handling without needing to write any of that repetitive, common boilerplate handling logic manually themselves.
Likely follow-ups
- What is the difference between StateProvider and the somewhat more capable StateNotifierProvider?
- How do you properly handle a genuine error that actually occurs within a FutureProvider?
Related topics