flutter_resultable 0.0.3
flutter_resultable: ^0.0.3 copied to clipboard
A lightweight Result type for modeling success/failure in Flutter and Dart using sealed classes.
flutter_resultable #
A lightweight, expressive Result type for Flutter and Dart to model success and failure outcomes without using exceptions, inspired by functional programming patterns like Either.
β¨ Features #
- β
Result.success(S)andResult.failure(F)to represent outcomes cleanly. - π Pattern matching via
when,map, andmaybeWhen(thanks tofreezed). - β‘ Strongly typed failure and success handling.
- π§ Utility extensions:
isSuccess,isFailuresuccessOrNull,failureOrNullgetOrElse(fallback)fold(onFailure, onSuccess)
- π‘ Easily testable and composable.
- πͺΆ Minimal, clean API.
π¦ Installation #
Add this to your pubspec.yaml:
dependencies:
flutter_resultable: ^0.0.3
Then run:
flutter pub get
π§ Usage #
Define a result-returning function #
import 'package:flutter_resultable/flutter_resultable.dart';
Result<String, int> divide(int a, int b) {
if (b == 0) return Result.failure("Division by zero");
return Result.success(a ~/ b);
}
Handle with pattern matching #
final result = divide(10, 2);
result.when(
failure: (error) => print("Error: $error"),
success: (value) => print("Result: $value"),
);
Use maybeWhen for optional handling #
result.maybeWhen(
success: (value) => print("Success with $value"),
orElse: () => print("Something went wrong"),
);
Use fold for cleaner branching #
result.fold(
(error) => print("Error: $error"),
(value) => print("Value: $value"),
);
Use getOrElse to provide a fallback value #
final value = result.getOrElse((error) => -1); // returns 5 or -1
Check result state or access nullable values #
if (result.isSuccess) {
print(result.successOrNull);
} else {
print(result.failureOrNull);
}
π API #
sealed class Result<F, S> {
const factory Result.failure(F failure) = Failure<F, S>;
const factory Result.success(S success) = Success<F, S>;
}
Utility Extensions #
| Extension | Description |
|---|---|
isSuccess |
Returns true if the result is success |
isFailure |
Returns true if the result is failure |
successOrNull |
Returns success value or null |
failureOrNull |
Returns failure value or null |
getOrElse |
Fallback mechanism based on failure value |
fold |
Branching on both success and failure cases |
π° Support #
If you find this project helpful, consider sponsoring me on GitHub π
π Contributing #
Contributions, ideas, and pull requests are welcome. Letβs make flutter_resultable better together!
π Thanks #
This package is powered by the amazing freezed package.
Special thanks to Remi Rousselet and contributors for their work.
Without freezed, clean and expressive sealed classes like Result wouldn't be this simple β¨
π License #
MIT License