Flutter › State Management with Riverpod

How do you properly handle loading, error, and data states when working with a FutureProvider or a StreamProvider in Riverpod, using the resulting AsyncValue's own convenient when method?

Intermediate

Answer

A FutureProvider or a StreamProvider exposes its own current value as an AsyncValue, which properly represents one of three distinct possible states, genuinely loading, a genuine error, or genuinely available data, and calling the AsyncValue's own convenient when method lets you provide a genuinely separate specific widget builder function for each one of those three particular distinct states, ensuring your interface correctly and appropriately handles every single possible outcome without needing to write repetitive, genuinely error prone manual conditional checks yourself.
userProvider.when(
  data: (user) => Text(user.name),
  loading: () => CircularProgressIndicator(),
  error: (err, stack) => Text('Error: $err'),
)
Real-world example A profile screen properly uses AsyncValue's own when method to cleanly display a loading spinner, a genuinely clear error message, or the actual user's own profile data depending on the exact current specific state of the underlying userProvider, all without needing to write any repetitive manual conditional checks themselves.

Common follow-ups: What is the specific practical difference between the when method and the somewhat similar maybeWhen method?;How does AsyncValue genuinely handle a scenario where the underlying data genuinely refreshes while some previous existing data is still genuinely currently being displayed?