How to extract Left or Right easily from Either type in Dart (Dartz) How to extract Left or Right easily from Either type in Dart (Dartz) flutter flutter

How to extract Left or Right easily from Either type in Dart (Dartz)


Ok here the solutions of my problems:

To extract/retrieve the data

final Either<ServerException, TokenModel> result = await repository.getToken(...);result.fold( (exception) => DoWhatYouWantWithException,  (tokenModel) => DoWhatYouWantWithModel);//Other way to 'extract' the dataif (result.isRight()) {  final TokenModel tokenModel = result.getOrElse(null);}

To test the exception

//You can extract it from below, or test it directly with the typeexpect(() => result, throwsA(isInstanceOf<ServerException>()));


I can't post a comment... But maybe you could look at this post. It's not the same language, but looks like it's the same behaviour.

Good luck.


Another way to extract the value is simply to convert to Option, then to a dart nullable:

final Either<Exception, String> myEither = Right("value");if (myEither.isRight()) {  final myString = myEither.toOption().toNullable()!;  print(myString); // "value"}

If you like you can define a simple extension to shortcut this:

extension EitherHelpers<L, R> on Either<L, R> {  R? unwrapRight() {    return toOption().toNullable();  }}