Result Type은 성공 시 값 또는 오류와 함께 실패할 수 있는 작업을 처리하는 강력하고 타입 안전한 방법을 제공하는 Dart 패키지입니다. 함수형 프로그래밍 개념에서 영감을 받아 계산 결과를 나타내기 위해 `Result<T, E>` 클래스를 도입하여 오류 처리를 더 명확하게 하고 예외 사용을 줄였습니다. 체이닝, 매핑 및 오류 전파를 지원하여 코드의 가독성과 유지보수성을 향상시킵니다. 명확한 성공/실패 상태가 필수적인 비즈니스 로직 및 데이터 처리 워크플로에 적합합니다.
import'dart:math';
import'package:http/http.dart'as http;
import'package:result_type/src/result.dart';
import'imaginary_service.dart';
import'photo.dart';
import'photos_service.dart';
final client = http.Client();
final random = Random();
voidmain() async {
final photosResult = awaitPhotosService.getPhotos(client);
final photosOr = photosResult.unwrapOr([Photo.initial()]);
print(photosOr);
/// Use `switch` to handle both success and failure.final _ = switch (photosResult) {
Success(value: final data) => data,
Failure(value: final error) => 'Error: $error'
};
/// Do something with successful operation results or handle an error.if (photosResult.isSuccess) {
print('Photos Items: ${photosResult.success}');
} else {
print('Error: ${photosResult.failure}');
}
// Chain multiple asynchronous operations.final result1 = awaitImaginaryService.fetchData1();
final result2 = awaitImaginaryService.fetchData2(result1.success);
final result3 = awaitImaginaryService.fetchData2(result2.success);
// Print the result of the last operation: `Success: Default Data`print(result3.unwrapOr('Default Data'));
// This will throw an exception as `_handleResult`// has a case with 'Wrong Data'.//print(result3.unwrap());Stringlength(String string) => string.length.toString();
final unwrapOrElse = result3.unwrapOrElse('Default (((((Data)))))', length);
// Print the result of the last operation: `22`print(unwrapOrElse);
/// Apply transformation to successful operation results or handle an error.if (photosResult.isSuccess) {
final items = photosResult
.map(
(i) => i.where(
(j) => j.title.length > 60,
),
)
.success;
print('Number of Long Titles: ${items.length}');
} else {
print('Error: ${photosResult.failure}');
}
/// In this example, note the difference in the result of using `map` and/// `flatMap` with a transformation that returns an result type.Result<int, Exception> getNextInteger() => Success(random.nextInt(4));
Result<int, Exception> getNextAfterInteger(int n) =>
Success(random.nextInt(n + 1));
final nextIntegerNestedResults = getNextInteger().map(getNextAfterInteger);
print(nextIntegerNestedResults.runtimeType);
// Prints: Success<Result<int, Error>, dynamic>final nextIntegerUnboxedResults =
getNextInteger().flatMap(getNextAfterInteger);
print(nextIntegerUnboxedResults.runtimeType);
// Prints: Success<int, Error>/// Use completion handler / callback style API if you want to.awaitPhotosService.getPhotos(client)
..result((photos) {
// print('Photos: $photos');
}, (error) {
print('Error: $error');
});
}
To see examples of the following package in action:
cd example && dart run
Support
Post issues and feature requests on the GitHub issue tracker.
License
The source code is distributed under the MIT license.
See the LICENSE file for more info.