CodeBlanks Logo Icon CodeBlanks

AsyncValue

Model async state with AsyncValue.

What is AsyncValue?

AsyncValue is a class that models the three possible states of an asynchronous operation (data, loading, error) in a single object. It is constructed as AsyncValue.data(value), AsyncValue.loading() or AsyncValue.error(err, stack). This lets you represent async state with a single type.

final value = AsyncValue<int>.data(42);
value.when(
  data: (n) => print('Data: $n'),
  loading: () => print('Loading'),
  error: (e, s) => print('Error: $e'),
);

The when method

The when method takes three callbacks: data, loading and error. It calls whichever callback matches the current state. This is safer than checking states with if-else because it forces you to handle every case and keeps the code readable.

snapshot.when(
  data: (user) => Text(user.name),
  loading: () => CircularProgressIndicator(),
  error: (e, s) => Text('Error: $e'),
);

Practice Use AsyncValue.when

Create a value with AsyncValue<int>.data(42). With the when method, print n in data, 'Yükleniyor' in loading, and 'Hata' in error.

Starter code

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

void main() {
  // AsyncValue ile 42 değerini oluştur
  // when ile üç durumu işle
}

Sample solution

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

void main() {
  final value = AsyncValue<int>.data(42);
  value.when(
    data: (n) => print(n),
    loading: () => print('Yükleniyor'),
    error: (e, s) => print('Hata'),
  );
}

Expected output

42

Questions and answers

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

1 Which method of AsyncValue forces handling all three states?

  • maybeWhen
  • fold
  • map
  • when Correct answer

Explanation: The when method takes data, loading and error callbacks; you are expected to provide all three.

2 AsyncValue data state

Question
final value = AsyncValue<int>.____(42);
Answer
final value = AsyncValue<int>.data(42);

Explanation: The data constructor produces an AsyncValue holding the successful result.

3 AsyncValue states

Term Meaning
AsyncValue.data Data state
AsyncValue.loading Loading state
AsyncValue.error Error state
when Handles all three states

All lessons in Advanced