Created
May 25, 2023 03:36
-
-
Save nick45chen/2aad3b437dbf7dd39b1e8e1cfc0a7861 to your computer and use it in GitHub Desktop.
回傳資料的封裝
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
/// A generic class that holds a value or an exception. | |
class RequestResult<T> { | |
const RequestResult._(); | |
const factory RequestResult.success(T? data) = Success<T>; | |
const factory RequestResult.error(Exception exception) = Error<T>; | |
const factory RequestResult.nothing() = Nothing<T>; | |
} | |
/// A successful result. | |
class Success<T> extends RequestResult<T> { | |
const Success(this.data) : super._(); | |
final T? data; | |
} | |
/// An error result. | |
class Error<T> extends RequestResult<T> { | |
const Error(this.exception) : super._(); | |
final Exception exception; | |
} | |
class Nothing<T> extends RequestResult<T> { | |
const Nothing() : super._(); | |
} | |
extension ResultExtensions<T> on RequestResult<T> { | |
/// Returns the data if this is a successful result, or the given fallback otherwise. | |
T successOr(T fallback) { | |
if (this is Success<T>) { | |
return (this as Success<T>).data ?? fallback; | |
} else { | |
return fallback; | |
} | |
} | |
bool get isError => this is Error; | |
bool get isSuccess => this is Success; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment