Last active
August 14, 2023 14:34
-
-
Save jagomf/bce1110cc79f8db385a854e8fd9a8262 to your computer and use it in GitHub Desktop.
Handling output with stream states
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Originally by Simon Lightfoot | |
extension WhenAsyncSnapshot<T> on AsyncSnapshot<T> { | |
R when<R>({ | |
R Function()? empty, | |
R Function(dynamic error, StackTrace? stackTrace)? error, | |
R Function()? loading, | |
R Function(T value)? data, | |
}) { | |
if (hasData && data != null) // If we have data then lets display it no-matter what! | |
return data(requireData); | |
if (connectionState != ConnectionState.done && loading != null) // Are we are still loading? | |
return loading(); | |
else if (hasError && error != null) // Did we get an error? | |
return error(this.error, stackTrace); | |
else if (empty != null) // No data, not loading, no error, we're empty! | |
return empty(); | |
else // We only get here if the developer does not provide any parameters | |
throw UnsupportedError('Missing parameters to when()'); | |
} | |
} | |
/// It can be used like this: | |
StreamBuilder( | |
stream: _stream, | |
builder: (BuildContext context, AsyncSnapshot<int> snapshot) { | |
return snapshot.when( | |
empty: () => Text('no data'), | |
error: (error, _) => ErrorWidget(error), | |
loading: () => Center(child: CircularProgressIndicator()), | |
data: (data) => Text('$data'), | |
); | |
}, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment