mapOrElse<N> method

N? mapOrElse<N>({
  1. N ok(
    1. T
    )?,
  2. N nullValue(
    1. T
    )?,
  3. N err(
    1. Object
    )?,
  4. N pending()?,
})

Unboxes the snapshot by applying different functions based on the state. This is extremely useful for building UIs!

ok - Called when snapshot has a value nullValue - Called when snapshot value is null (if both ok and nullValue are provided, nullValue is preferred for null values) err - Called when snapshot has an error pending - Called when snapshot is pending

Returns the result of applying the corresponding function, or null if no matching handler is provided.

Example:

snapshot.mapOrElse(
  ok: (value) => Text('Value: $value'),
  err: (error) => Text('Error: $error'),
  pending: () => CircularProgressIndicator(),
);

Implementation

N? mapOrElse<N>({
  N Function(T)? ok,
  N Function(T)? nullValue,
  N Function(Object)? err,
  N Function()? pending,
}) {
  if (isPending()) {
    return pending != null ? pending() : null;
  }

  if (isErr()) {
    return err != null ? err(error!) : null;
  }

  final ret = data as T;
  final fn = (ret != null) ? ok : (nullValue ?? ok);

  return fn != null ? fn(ret) : null;
}