H.org
  • Questions

Dartz: Using Either

  1. dart
  2. dartz
  3. functional-programming

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();
}
Ko-Fi button Support Me on Ko-fi

Created with lots of green tea and 11ty

Opinions are solely my own and not those of my employer.

Privacy Policy - Licenses