Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I am looking to extract a value easily from a method that return a type Either<Exception, Object>.

I am doing some tests but unable to test easily the return of my methods.

For example:

final Either<ServerException, TokenModel> result = await repository.getToken(...); 

To test I am able to do that

expect(result, equals(Right(tokenModelExpected))); // => OK 

Now how can I retrieve the result directly?

final TokenModel modelRetrieved = Left(result); ==> Not working.. 

I found that I have to cast like that:

final TokenModel modelRetrieved = (result as Left).value; ==> But I have some linter complain, that telling me that I shouldn't do as to cast on object... 

Also I would like to test the exception but it's not working, for example:

expect(result, equals(Left(ServerException()))); // => KO 

So I tried this

expect(Left(ServerException()), equals(Left(ServerException()))); // => KO as well, because it says that the instances are different. 
like image 579
Maurice Avatar asked Nov 06 '19 15:11

Maurice


People also ask

How do you use either in darts?

Either<int, String> response = Right("Hello, im right"); This is how simple it is to use Either(), you declare the Left and Right type inside the generic type parameters in the respective order. To assign value use Left(value) or Right(value) .

Is Flutter functional programming?

Functional programming in Dart and Flutter. All the main functional programming types and patterns fully documented, tested, and with examples. Fpdart is fully documented. You do not need to have any previous experience with functional programming to start using fpdart .

How do you define a function in Flutter?

A function (also might be referenced to as method in the context of an object) is a subset of an algorithm that is logically separated and reusable. It can return nothing (void) or return either a built-in data type or a custom data type. It can also have no parameters or any number of parameters.


2 Answers

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 data if (result.isRight()) {   final TokenModel tokenModel = result.getOrElse(null); } 

To test the exception

//You can extract it from below, or test it directly with the type expect(() => result, throwsA(isInstanceOf<ServerException>())); 
like image 157
Maurice Avatar answered Sep 28 '22 09:09

Maurice


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.

like image 24
user8939092 Avatar answered Sep 28 '22 10:09

user8939092