A Dart package with the type
Result and the
runCatching function that are similar to those found in Kotlin.
I needed something as is done in
Kotlin and did not want to add other functions that not are used in my projects.
There is another package similar, result, however, it was discontinued.
Add it in your
Import it where you want to use it e.g, in your main file.
Result.success(0) .onSuccess( action: print, ) .onFailure( action: (failure) => print( failure.error.toString(), ), ); Result<int>.failure(Exception(), StackTrace.current) .onSuccess( action: print, ) .onFailure( action: (failure) => print( failure.error.toString(), ), );
See the API documentation.
Execute a passed function and catches any
error that is thrown from this execution, if the invocation is successful, then returns your
value encapsulated in the
Result, otherwise, returns your
stack trace encapsulated in the
final result = runCatching(() => 1); result .onSuccess( action: print, ) .onFailure( action: (failure) => print( failure.error.toString(), ), );
Note: You can be passed what
error type you want catching, if the same, then return the
Result, otherwise, the error is rethrown.
final result = runCatching<int>( () => throw 'exception', test: (error) => error is Exception, ), // `onFailure` is never called result .onFailure( action: (failure) => print( failure.error.toString(), ), );
Other similar packages
The dartz package offers many functional programming helpers, including the Either type, which is similar to Result, with the difference being that it represents any two types of values.
The either_option package has Either and Option and supports all of the typical functional operations.
The result package offers a few basic operations and may be adequate for simple cases (This package has been two years without any updates).
The rust_like_result offers a simple Result type similar to the one in Rust.
The simple_result package provides a Result type based on the type of the same name in Swift.
The oxidized with types similar to those found in Rust, such as the Result which represents either a value or an error, and Option which either contains Some value or None.
You liked this package? Then give it a ⭐️. If you want to help then:
- Fork this repository
- Send a Pull Request with new features
- Share this package
- Create issues if you find a bug or want to suggest a new extension
Pull Request title follows Conventional Commits.