搜尋套件、儲存庫與 APP 分類

套件詳情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 類型不熟悉,則需要學習新的模式
  • 在簡單情況下可能會增加語氣
  • 不適合用於底層系統錯誤
  • 與某些現有的基於例外的程式庫整合有限
  • 最好與空安全實踐結合使用

原始 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 項

原始碼儲存庫

使用此套件的專案

暫無相關資料。