패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.0.0

result_type

Dart용 결과 유형입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
4.9천
좋아요
35
Pub 점수
150

패키지 설치

flutter pub add result_type

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Result Type은 성공 시 값 또는 오류와 함께 실패할 수 있는 작업을 처리하는 강력하고 타입 안전한 방법을 제공하는 Dart 패키지입니다. 함수형 프로그래밍 개념에서 영감을 받아 계산 결과를 나타내기 위해 `Result<T, E>` 클래스를 도입하여 오류 처리를 더 명확하게 하고 예외 사용을 줄였습니다. 체이닝, 매핑 및 오류 전파를 지원하여 코드의 가독성과 유지보수성을 향상시킵니다. 명확한 성공/실패 상태가 필수적인 비즈니스 로직 및 데이터 처리 워크플로에 적합합니다.

사용 사례

  • API 응답 처리
  • 사용자 입력 검증 처리
  • 비동기 작업 관리
  • 명시적 오류를 사용한 비즈니스 로직 구현
  • try-catch 블록을 구조화된 흐름으로 대체하기

주요 기능

  • 타입 안전한 성공 및 오류 유형
  • 체이닝 및 변환 메서드
  • 내장 오류 전파
  • 조합 가능한 결과 처리
  • 최소한의 보일러플레이트

적합한 대상

  • Dart에서 함수형 패턴을 사용하는 개발자
  • 명확한 오류 처리가 필요한 프로젝트
  • 예측 가능한 상태 관리를 목표로 하는 팀
  • 복잡한 데이터 흐름을 가진 애플리케이션
  • 제어 흐름을 위한 예외의 대안을 찾는 사람들

고려 사항

  • Result 유형에 익숙하지 않으면 새로운 패턴을 배워야 합니다
  • 간단한 경우에서 verbosity가 증가할 수 있음
  • 저수준 시스템 오류에 적합하지 않습니다
  • 일부 기존 예외 기반 라이브러리와의 통합 제한
  • null 안전성 관행과 함께 사용하는 것이 가장 좋습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Result Type for Dart

CI Status Result Type is released under the MIT license. PRs welcome!

Content

Features

Result is a type that represents either Success or Failure.

Inspired by functional programming, Rust and Swift.

Requirements

  • Dart: 3.3.0+

Install

dependencies:
  result_type: ^1.0.0

Example

The detailed example can be found at result_type/example/example.dart.

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();

void main() async {
  final photosResult = await PhotosService.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 = await ImaginaryService.fetchData1();
  final result2 = await ImaginaryService.fetchData2(result1.success);
  final result3 = await ImaginaryService.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());

  String length(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.
  await PhotosService.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.

카테고리

의존성

의존성 목록 1 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.