maybeWhen<R> method

R maybeWhen<R>({
  1. R data(
    1. T data,
    2. bool isComplete
    )?,
  2. required R error(
    1. Object error,
    2. StackTrace? stackTrace
    ),
  3. required R loading(),
})

Perform conditional actions based on the state of the AsyncSnapshot.

Key points:

-️ Similar to when, but allows data callback to be optional. -️ If no data callback, calls loading callback instead. -️ isComplete signifies a closed connection/stream.

Example:

StreamBuilder(
  stream: incomingMessagesStream,
  builder: (context, snapshot) {
    return snapshot.maybeWhen(
      data: (data, isComplete) {
        return Column(
          children: [
            Text('Latest Message: $data'),
            if (isComplete) Text('Messages are complete'),
          ],
        );
      },
      error: (error, stackTrace) {
        return Text('We have an error');
      },
      loading: () {
        return CircularProgressIndicator();
      },
    );
  },
);

Implementation

R maybeWhen<R>({
  R Function(T data, bool isComplete)? data,
  required R Function(Object error, StackTrace? stackTrace) error,
  required R Function() loading,
}) {
  switch (connectionState) {
    case ConnectionState.none:
      if (this.data is T) {
        return data!(this.data as T, true);
      } else {
        return loading();
      }
    case ConnectionState.waiting:
      return loading();
    case ConnectionState.active:
      if (hasError) {
        return error(this.error!, stackTrace);
      } else {
        return data!(this.data as T, false);
      }
    case ConnectionState.done:
      if (hasError) {
        return error(this.error!, stackTrace!);
      } else {
        return data!(this.data as T, true);
      }
  }
}