Result Dart는 Kotlin과 Swift의 Result 유형에서 영감을 받은 Dart 패키지로, 성공하거나 실패할 수 있는 작업을 안전하게 처리할 수 있도록 도와줍니다. 성공한 값(Ok) 또는 오류(Err)를 캡슐화하여 명시적인 에러 처리를 장려하고 예외 사용을 줄입니다. 이 패키지는 성공 및 실패 사례를 명시적으로 다루도록 개발자를 유도함으로써 코드의 가독성과 신뢰성을 향상시킵니다. Dart의 async/await 구문과 원활하게 통합되며, map, flatMap, fold와 같은 함수형 프로그래밍 패턴을 지원합니다.
사용 사례
API 응답 처리
오류 상태를 사용하여 비동기 작업 관리
try-catch 블록을 명시적인 결과 처리로 대체하기
명확한 성공/실패 경로를 사용하여 비즈니스 로직 구현
오류가 발생하기 쉬운 함수의 테스트 가능성 향상
주요 기능
불변 결과 유형
기능 조합자 (map, flatMap, fold)
명시적인 오류 및 성공 상태
async/await와의 원활한 통합
널 안전성 지원
적합한 대상
더 안전한 오류 처리를 찾는 개발자
기능형 프로그래밍에 중점을 두는 프로젝트
패턴 매칭 유사 워크플로를 채택하는 팀
강력한 상태 관리가 필요한 애플리케이션
Kotlin 또는 Swift에 익숙한 Dart 개발자
고려 사항
Result 유형 패턴에 익숙하지 않은 개발자를 위한 학습 곡선
간단한 경우에서의 잠재적인 과도한 설명
진정으로 예외적인 상황에서는 예외의 대체가 될 수 없습니다
강하게 결합된 코드에서는 추가적인 보일러플레이트가 필요할 수 있습니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
RESULT_DART
This package aims to create an implemetation of Kotlin's and Swift's Result class and own operators.
Inspired by `multiple_result` package, the `dartz` package and the `fpdart` package.
Explore the docs »
Overruns are common in design, and modern architectures always designate a place to handle failures.
This means dramatically decreasing try/catch usage and keeping treatments in one place.
But the other layers of code need to know about the two main values [Success, Failure]. The solution lies in the
Result class pattern implemented in Kotlin and Swift and now also in Dart via this package(result_dart).
This project is distributed under the MIT License. See LICENSE for more information.
This version aims to reduce the Result boilerplate by making the Failure type Exception by default. This will free the Result from having to type Failure, making the declaration smaller.
To get result_dart working in your project follow either of the instructions below:
a) Add result_dart as a dependency in your Pubspec.yaml:
dependencies:result_dart:x.x.x
b) Use Dart Pub:
dart pub add result_dart
How to Use
In the return of a function that you want to receive an answer as Sucess or Failure, set it to return a Result type;
ResultgetSomethingPretty();
then add the Success and the Failure types.
Result<String> getSomethingPretty() {
}
In the return of the above function, you just need to use:
// Using Normal instancereturnSuccess('Something Pretty');
// import 'package:result_dart/functions.dart'returnsuccessOf('Something Pretty');
// Using extensionsreturn'Something Pretty'.toSuccess();
or
// Using Normal instancereturnFailure(Exception('something ugly happened...'));
// import 'package:result_dart/functions.dart'returnfailureOf('Something Pretty');
// Using extensionsreturn'something ugly happened...'.toFailure();
IMPORTANT NOTE: The toSuccess() and toFailure() methods cannot be used on a Result object or a Future. If you try, will be throw a Assertion exception.
Handling the Result with fold:
Returns the result of onSuccess for the encapsulated value
if this instance represents Success or the result of onError function
for the encapsulated value if it is Failure.
voidmain() {
final result = getSomethingPretty();
finalString message = result.fold(
(success) {
// handle the success herereturn"success";
},
(failure) {
// handle the failure herereturn"failure";
},
);
}
Handling the Result with getOrThrow
Returns the success value as a throwing expression.
voidmain() {
final result = getSomethingPretty();
try {
final value = result.getOrThrow();
} onExceptioncatch(e){
// e
}
}
Handling the Result with getOrNull
Returns the value of [Success] or null.
voidmain() {
final result = getSomethingPretty();
result.getOrNull();
}
Handling the Result with getOrElse
Returns the encapsulated value if this instance represents Success
or the result of onFailure function for
the encapsulated a Failure value.
voidmain() {
final result = getSomethingPretty();
result.getOrElse((failure) => 'OK');
}
Handling the Result with getOrDefault
Returns the encapsulated value if this instance represents
Success or the defaultValue if it is Failure.
voidmain() {
final result = getSomethingPretty();
result.getOrDefault('OK');
}
Handling the Result with exceptionOrNull
Returns the value of [Failure] or null.
voidmain() {
final result = getSomethingPretty();
result.exceptionOrNull();
}
Transforming a Result
Mapping success value with map
Returns a new Result, mapping any Success value
using the given transformation.
voidmain() {
final result = getResult()
.map((e) => MyObject.fromMap(e));
result.getOrNull(); //Instance of 'MyObject'
}
Mapping failure value with mapError
Returns a new Result, mapping any Error value
using the given transformation.
voidmain() {
final result = getResult()
.mapError((e) => MyException(e));
result.exceptionOrNull(); //Instance of 'MyException'
}
Chain others [Result] by any Success value with flatMap
Returns a new Result, mapping any Success value
using the given transformation and unwrapping the produced Result.
Chain others [Result] by Failure value with flatMapError
Returns a new Result, mapping any Error value
using the given transformation and unwrapping the produced Result.
voidmain() {
final result = getNumberResult()
.flatMapError((e) => checkError(e));
}
Resolve [Result] by Failure value with recover
Returns the encapsulated Result of the given transform function
applied to the encapsulated a Failure or the original
encapsulated value if it is success.
voidmain() {
final result = getNumberResult()
.recover((f) => Success('Resolved!'));
}
Conditionally resolve [Result] by Failure value with recoverWhen
Returns the encapsulated Result of the given transform function
applied to the encapsulated a Failureonly if the test predicate returns true.
Otherwise, returns the original Failure unchanged.
If this is a Success, returns it unchanged.
voidmain() {
final result = getNumberResult()
.recoverWhen(
(f) => f isTimeoutException,
(f) => Success('Recovered from timeout!'),
);
// Only recovers TimeoutException, other failures propagate unchanged
}
Inspect a [Result] with tap
Performs the given action on the Result regardless of whether it
is a Success or Failure. Returns the original Result unchanged.
Useful for debugging and logging intermediate states in a chain.
voidmain() {
final result = getNumberResult()
.tap((r) => print('Step 1: $r'))
.flatMap((s) => validateNumber(s))
.tap((r) => print('Step 2: $r'));
}
Filter a Success value with filter
Returns this Result if it is a Failure or if the predicate
returns true for the encapsulated Success value.
Otherwise, returns a Failure created by orElse.
voidmain() {
final result = getNumberResult()
.filter(
(n) => n > 0,
(n) => Exception('$n is not positive'),
);
}
Combine two [Result]s with zip
Combines this Result with another into a single Result
containing a Record of both success values.
If either is a Failure, returns the first Failure encountered.
voidmain() {
final name = Success<String, Exception>('Jacob');
final age = Success<int, Exception>(25);
final combined = name.zip(age);
// Success(('Jacob', 25))
combined.map((record) {
final (n, a) = record;
return'Name: $n, Age: $a';
});
}
Flatten a nested [Result] with flatten
Unwraps a ResultDart<ResultDart<S, F>, F> into a ResultDart<S, F>,
removing one level of nesting.
voidmain() {
final nested = Success<ResultDart<int, String>, String>(Success(42));
final flat = nested.flatten();
// Success(42)
}
Add a pure Success value with pure
Change the [Success] value.
voidmain() {
final result = getSomethingPretty().pure(10);
String? mySuccessResult;
if (result.isSuccess()) {
mySuccessResult = result.getOrNull(); // 10
}
}
Add a pure Failure value with pureError
Change the [Failure] value.
voidmain() {
final result = getSomethingPretty().pureError(10);
if (result.isFailure()) {
result.exceptionOrNull(); // 10
}
}
Swap a Result with swap
Swap the values contained inside the [Success] and [Failure]
of this [Result].
Some results do not need a specific return. Use the Unit type to signal an empty return.
Result<Unit>
Help with functions that return their parameter:
NOTE: use import 'package:result_dart/functions.dart'
Sometimes it is necessary to return the parameter of the function as in this example:
final result = Success(0);
String value = result.when((s) => '$s', (e) => e);
print(string) // "0";
We can use the identity function or its acronym id to facilitate the declaration of this type of function that returns its own parameter and does nothing else:
final result = Success(0);
// changed `(e) => e` by `id`String value = result.when((s) => '$s', id);
print(string) // "0";
Use AsyncResult type:
AsyncResult<S, E> represents an asynchronous computation.
Use this component when working with asynchronous Result.
AsyncResult has some of the operators of the Result object to perform data transformations (Success or Failure) before executing the Future.
All Result operators is available in AsyncResult
AsyncResult<S, E> is a typedef of Future<Result<S, E>>.
AsyncResult<String> fetchProducts() async {
try {
final response = await dio.get('/products');
final products = ProductModel.fromList(response.data);
returnSuccess(products);
} onDioErrorcatch (e) {
returnFailure(ProductException(e.message));
}
}
...
final state = awaitfetch()
.map((products) => LoadedState(products))
.mapLeft((failure) => ErrorState(failure))
When chaining many operations with recover, errors from earlier steps may be accidentally recovered. To avoid this, group related operations into their own functions:
// ❌ Avoid: recover may catch unrelated errorsfetchUser()
.flatMap(fetchOrders)
.flatMap(validateOrders)
.recover(fallbackOrders) // may recover a fetchUser error!
.flatMap(processOrders);
// ✅ Prefer: scope the recovery to the relevant operationsAsyncResult<Orders> getValidOrders() {
returnfetchUser()
.flatMap(fetchOrders)
.flatMap(validateOrders)
.recover(fallbackOrders); // only recovers validation/fetch errors
}
getValidOrders()
.flatMap(processOrders);
Alternatively, use recoverWhen to recover only specific error types:
The Failure type is a generic container and does not capture stack traces.
If you need stack traces for debugging, capture them in your custom Exception classes:
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the appropriate tag.
Don't forget to give the project a star! Thanks again!
Fork the Project
Create your Feature Branch (git checkout -b feature/AmazingFeature)
Commit your Changes (git commit -m 'Add some AmazingFeature')
Push to the Branch (git push origin feature/AmazingFeature)