パッケージ、リポジトリ、アプリカテゴリを検索

パッケージ詳細v1.0.0

result_type

Dart用の結果タイプ。

AndroidiOSWebmacOSWindowsLinux
30日間ダウンロード
4850
いいね数
35
Pub ポイント
150

パッケージをインストール

flutter pub add result_type

パッケージ概要

公開情報に基づく選定ガイドです。参考としてご利用ください。

Result Type は、Dart パッケージで、成功時に値を返すか、失敗時にエラーを返す操作を堅牢かつ型安全に扱う方法を提供します。関数型プログラミングのコンセプトからインスパイアされ、`Result<T, E>` クラスを導入して計算の結果を表し、エラー処理をより明示的にし、例外の使用を減らします。チェーン、マッピング、エラーの伝播をサポートしており、コードの読みやすさと保守性を向上させます。明確な成功/失敗状態が必要なビジネスロジックやデータ処理ワークフローに最適です。

用途

  • API レスポンスの処理
  • ユーザー入力検証の処理
  • 非同期操作の管理
  • 明示的なエラーを使用したビジネスロジックの実装
  • try-catch ブロックを構造化されたフローに置き換える

主な機能

  • 型安全な成功とエラーの種類
  • チェーン処理と変換メソッド
  • 組み込みエラーフォローアップ
  • 組み合わせ可能な結果処理
  • 最小限のボイラープレート

適している対象

  • Dartで関数型パターンを使用する開発者
  • 明確なエラーハンドリングを必要とするプロジェクト
  • 予測可能な状態管理を目指すチーム
  • 複雑なデータフローを持つアプリケーション
  • 制御フローのための例外の代替手段を模索する人々

注意事項

  • Result タイプに慣れていない場合、新しいパターンを学ぶ必要があります
  • 簡単なケースでは冗長性が増す可能性があります
  • 低レベルのシステムエラーには適していません
  • 一部の既存の例外ベースのライブラリとの統合が限定的
  • 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 件

ソースリポジトリ

このパッケージを使用しているプロジェクト

データはまだありません。