maybeWhen<R> method
R
maybeWhen<R>({
- R data(
- T data,
- bool isComplete
- required R error(
- Object error,
- StackTrace? stackTrace
- 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);
}
}
}