Created
September 30, 2020 13:11
-
-
Save minikin/1550abe4f921188ebfa005db5f0604df to your computer and use it in GitHub Desktop.
Result Type Dart
This file contains 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
void main() { | |
final item = {'1': 'Apple'}; | |
final operationSuccessed = Result.success(item); | |
final operationFailed = Result.error(Failure('Cannot catch data')); | |
print(operationSuccessed.result); | |
print(operationFailed.error); | |
} | |
class Result<Success, Error extends Failure> { | |
final Error error; | |
final Success result; | |
bool get isSuccess => error == null; | |
const Result.success(this.result) : error = null; | |
const Result.error(this.error) : result = null; | |
} | |
class Failure { | |
final String message; | |
const Failure(this.message); | |
@override | |
String toString() => message; | |
} |
@minkin nice one but I have question in real world scenario
Lets say I have a function like belwo
Result<String, Error> getData() {
return Result.success("Hello");
}
var result = getData();
result
will be of a Result type ... how can I determine if it was an error
or success
without using the boolean you have
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://dartpad.dev/1550abe4f921188ebfa005db5f0604df