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

套件詳情v2.2.0

result_dart

dart 的結果。這是基於 Kotlin Result 和 Swift Result 的實現。

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
6.3萬
喜歡數
175
Pub 分數
160

安裝套件

flutter pub add result_dart

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

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 »

Report Bug · Request Feature


Version Pub Points Flutterando Analysis

Pub Publisher



Table of Contents
  1. About The Project
  2. Getting Started
  3. How to Use
  4. Features
  5. Contributing
  6. Contact
  7. Acknowledgements


About The Project



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.

(back to top)

Migrate 1.1.1 to 2.0.0

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.

// Old
Result<int, Exception> myResult = Success(42);

// NEW
Result<int> myResult = Success(42);

if there is a need to type it, use ResultDart<Success, Failure>:

// Old
Result<int, String> myResult = Success(42);

// NEW
ResultDart<int, String> myResult = Success(42);

Getting Started

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;

Result getSomethingPretty();

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 instance
return Success('Something Pretty');

// import 'package:result_dart/functions.dart'
return successOf('Something Pretty');

// Using extensions
return 'Something Pretty'.toSuccess();

or

// Using Normal instance
return Failure(Exception('something ugly happened...'));

// import 'package:result_dart/functions.dart'
return failureOf('Something Pretty');

// Using extensions
return 'something ugly happened...'.toFailure();

The function should look something like this:


Result<String> getSomethingPretty() {
    if(isOk) {
        return Success('OK!');
    } else {
        return Failure(Exception('Not Ok!'));
    }
}

or when using extensions, like this:


Result<String> getSomethingPretty() {
    if(isOk) {
        return 'OK!'.toSuccess();
    } else {
        return Exception('Not Ok!').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.

void main() {
    final result = getSomethingPretty();
     final String message = result.fold(
        (success) {
          // handle the success here
          return "success";
        },
         (failure) {
          // handle the failure here
          return "failure";
        },
    );

}
Handling the Result with getOrThrow

Returns the success value as a throwing expression.

void main() {
    final result = getSomethingPretty();

    try {
     final value = result.getOrThrow();
    } on Exception catch(e){
      // e
    }
}

Handling the Result with getOrNull

Returns the value of [Success] or null.

void main() {
    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.

void main() {
    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.

void main() {
    final result = getSomethingPretty();
    result.getOrDefault('OK');
}

Handling the Result with exceptionOrNull

Returns the value of [Failure] or null.

void main() {
    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.

void main() {
    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.

void main() {
    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.


Result<String, MyException> checkIsEven(String input){
    if(input % 2 == 0){
        return Success(input);
    } else {
        return Failure(MyException('isn`t even!'));
    }
}

void main() {
    final result = getNumberResult()
        .flatMap((s) => checkIsEven(s));
}
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.


void main() {
    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.


void main() {
    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 Failure only if the test predicate returns true. Otherwise, returns the original Failure unchanged. If this is a Success, returns it unchanged.

void main() {
    final result = getNumberResult()
        .recoverWhen(
          (f) => f is TimeoutException,
          (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.

void main() {
    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.

void main() {
    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.

void main() {
    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.

void main() {
    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.

void main() {
    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.

void main() {
    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].

void main() {
    Result<String, int> result =...;
    Result<int, String> newResult = result.swap();
}
Unit Type

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);
      return Success(products);
    } on DioError catch (e) {
      return Failure(ProductException(e.message));
    }
}

...

final state = await fetch()
    .map((products) => LoadedState(products))
    .mapLeft((failure) => ErrorState(failure))


(back to top)

Features

  • ✅ Result implementation.
  • ✅ Result`s operators(map, flatMap, mapError, flatMapError, swap, when, fold, getOrNull, exceptionOrNull, isSuccess, isError).
  • ✅ AsyncResult implementation.
  • ✅ AsyncResult`s operators(map, flatMap, mapError, flatMapError, swap, when, fold, getOrNull, exceptionOrNull, isSuccess, isError).
  • ✅ Auxiliar functions (id, identity, success, failure).
  • ✅ Unit type.
  • ✅ tap operator for debugging and logging.
  • ✅ filter operator for conditional Success-to-Failure conversion.
  • ✅ zip operator for combining two Results using Dart 3 Records.
  • ✅ flatten operator for unwrapping nested Results.
  • ✅ recoverWhen operator for conditional recovery by predicate.

(back to top)

Best Practices

Scoped Recovery

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 errors
fetchUser()
  .flatMap(fetchOrders)
  .flatMap(validateOrders)
  .recover(fallbackOrders)  // may recover a fetchUser error!
  .flatMap(processOrders);

// ✅ Prefer: scope the recovery to the relevant operations
AsyncResult<Orders> getValidOrders() {
  return fetchUser()
    .flatMap(fetchOrders)
    .flatMap(validateOrders)
    .recover(fallbackOrders); // only recovers validation/fetch errors
}

getValidOrders()
  .flatMap(processOrders);

Alternatively, use recoverWhen to recover only specific error types:

fetchUser()
  .flatMap(fetchOrders)
  .flatMap(validateOrders)
  .recoverWhen(
    (f) => f is ValidationException,
    (f) => fallbackOrders(),
  )
  .flatMap(processOrders);
Custom Exceptions with StackTrace

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:

class AppException implements Exception {
  final String message;
  final StackTrace stackTrace;

  AppException(this.message) : stackTrace = StackTrace.current;

  @override
  String toString() => 'AppException: $message\n$stackTrace';
}

This way, the stack trace travels with the error through the Result chain, and tap can be used to inspect it:

fetchData()
  .tap((r) => print(r))  // prints "Failure(AppException: ...)" with stack
  .flatMap(process);

(back to top)

Contributing

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!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Remember to include a tag, and to follow Conventional Commits and Semantic Versioning when uploading your commit and/or creating the issue.

(back to top)

Contact

Flutterando Community

(back to top)

Acknowledgements

Thank you to all the people who contributed to this project, whithout you this project would not be here today.


(back to top)

Maintaned by


Built and maintained by Flutterando.

所屬分類

依賴

依賴清單 1 項

原始碼儲存庫

使用此套件的專案