result_dart 1.0.0+1 copy "result_dart: ^1.0.0+1" to clipboard
result_dart: ^1.0.0+1 copied to clipboard

Result for dart. It is an implementation based on Kotlin Result and Swift Result.

RESULT_DART


This package aims to create an implemetation of Kotlin's and Swift's Result class and own operators. Inspired by Higor Lapa's 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. Sponsors
  3. Getting Started
  4. How to Use
  5. Features
  6. Contributing
  7. Contact
  8. 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 is in 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)

Sponsors #

Logo

(back to top)


Getting Started #

To get your_package in your project follow either of the instructions below:

a) Add your_package 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, set it to return a Result type;

Result getSomethingPretty();

then add the Success and the Failure types.


Result<String, Exception> getSomethingPretty() {

}

in return of the function, you just need to return

// Using Normal instance
return Success('Something Pretty');

// Using Result factory
return Result.success('Something Pretty');

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

or

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

// Using Result factory
return Result.failure('something ugly happened...');

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

The function should look something like this:


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

or this (using extensions):


Result<String, Exception> getSomethingPretty() {
    if(isOk) {
        return 'OK!'.toSuccess();
    } else {
        return Exception('Not Ok!').toFailure();
    }
}

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 when or fold:

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

}

** OBS: As we are going through a transition process, the when and fold syntax are identical. Use whichever one you feel most comfortable with and help us figure out which one should remain in the pack.

Handling the Result with get

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

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

Handling the Result with getOrNull

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

    String? mySuccessResult;
    if (result.isSuccess()) {
      mySuccessResult = result.getOrNull();
    }
}

Handling the Result with exceptionOrNull

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

    Exception? myException;
    if (result.isFailure()) {
      myException = result.exceptionOrNull();
    }
}

Transforming a Result #

Mapping success value with map

void main() {
    final result = getResult()
        .map((e) => MyObject.fromMap(e));

    result.getOrNull(); //Instance of 'MyObject' 
}

Mapping failure value with mapError

void main() {
    final result = getResult()
        .mapError((e) => MyException(e));

    result.exceptionOrNull(); //Instance of 'MyException'

}

Chain others [Result] by any Success value with flatMap


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


void main() {
    final result = getNumberResult()
        .flatMapError((e) => checkError(e));
}

Add a pure Success value with pure

void main() {
    final result = getSomethingPretty().pure(10);

    String? mySuccessResult;
    if (result.isSuccess()) {
      mySuccessResult = result.getOrNull(); // 10
    }
}

Add a pure Failure value with pureError

void main() {
    final result = getSomethingPretty().pureError(10);
    if (result.isFailure()) {
       result.exceptionOrNull(); // 10
    }
}

Swap a Result with swap

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, Exception>

Help with functions that return their parameter: #

Sometimes it is necessary to return the parameter of the function as in this example:

final result = Success<int, String>(0);

String value = result.when((s) => '$s', (e) => e);
print(string) // "0";

Now 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<int, String>(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, Exception> 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.

(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.

91
likes
0
pub points
91%
popularity

Publisher

verified publisherflutterando.com.br

Result for dart. It is an implementation based on Kotlin Result and Swift Result.

Repository (GitHub)
View/report issues

License

unknown (LICENSE)

Dependencies

meta

More

Packages that depend on result_dart