Last updated:
0 purchases
resource result
Provides a Resource class containing data of any type and an error of any type. This allows methods
to return a Resource<T> which can be a Success, Loading or Failure instead of returning
a T and throwing an Exception if the method fails. Additionally, if a method returns a Future
or Stream the Loading state can initially be returned.
Usage #
To return a resource from a method: #
Synchronous
Resource<int> parseInt(String value) {
try {
return Success(int.parse(value));
} catch (e) {
return Failure.fromMessage("Failed to parse value '$value'");
}
}
copied to clipboard
Asynchronous
convert(someStream).listen((resource) {
resource.resolve(
onSuccess: (someClassData) => Text(
"Converted someClass to otherClass instance successfully: $someClassData"),
onLoading: (_) => Text("Loading..."),
onFailure: (error) => Text("Failed to convert: $error")
);
});
copied to clipboard
Use Resource result #
final Resource<int> result = parseInt("13");
if (result.hasData) {
Text("Parsed int successfully: ${result.data}");
} else {
Text("Failed to parse int: ${result.error?.message}");
}
//or
Stream<Resource<OtherClass>> convert(Stream<SomeClass> toConvert) async* {
yield Loading(EmptyOtherClass());
await for (final someObject in toConvert) {
try {
final OtherClass converted = convertToSomeObject(someObject);
yield Success(converted);
} catch (e) {
yield Failure.fromMessage("Failed convert '$someObject'");
}
}
}
copied to clipboard
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.