State ManagementEasy20 XP3 min read
What is AsyncValue in Riverpod and how do you use it?
TL;DR: AsyncValue<T> is Riverpod's sealed class representing three states: loading, data(T), and error. It simplifies handling async operations without manual loading/error boolean fields.
Full Answer
AsyncValue eliminates the need for manual isLoading, error, and data flags. It's automatically produced by FutureProvider and StreamProvider.
- ▸AsyncValue.loading() — operation in progress
- ▸AsyncValue.data(value) — operation succeeded with a value
- ▸AsyncValue.error(error, stackTrace) — operation failed
- ▸.when(data:, loading:, error:) — pattern-match all three cases
- ▸.whenData((v) => ...) — transforms only the data case
- ▸.isLoading, .hasValue, .hasError — boolean accessors
🎯
Use .requireValue when you're certain data is available (e.g., after a guard check) to avoid null checks. Throws if not in data state.
Code Examples
dartAsyncValue.when usage
Output
Shows spinner while loading, error text on failure, ListView with post titles on success
Common Mistakes
- ✗Using ref.read(provider) inside build() — use ref.watch() to react to state changes
- ✗Forgetting the error case in .when() — required parameter; compiler enforces it
Interview Tip
💡
Compare AsyncValue to manual loading/error flags to show WHY it's an improvement, not just HOW to use it.
#Riverpod#AsyncValue#loading#error#data#FutureProvider