Dartz: Using Either
The dartz package includes classes for programming in a functional style.
Either
allows you to represent a choice between two different types and is mostly used in error handling.
Examples
Simply return type Either<,>
with the types you are expecting:
Future<Either<NetworkError, User>> login(...) async {
// perform login steps
var response = await ...
if (response.status >= 200 && response.status < 300) {
return right(response.data);
} else {
return left(NetworkError(response.statusCode));
}
}
Notice the two methods left
and right
? These are how you return the specific result for the given Either. Left represents the error value and right the expected value. As you can see, the API is really simple to work with.
In order to get some kind of result out of the Either, one method is to fold
it:
final Either<NetworkError, User> loginResult = await gateway.login(...);
loginResult.fold(
(error) => handleError,
(user) => handleComplete
);
You can also use isLeft
and isRight
methods to check the result in a more imperative way:
if (loginResult.isLeft()) {
handleError();
}
if (loginResult.isRight()) {
handleComplete();
}