Flutter Dartz Either Type & Error Handling | Dart Programming

Created At: 2023-08-25 18:21:34 Updated At: 2023-08-28 15:43:59

Dartz is Flutter or Dart package for handling error. This is very suitable when you do clean architecture and want to catch the error or success separately.

To install Dartz you can run

flutter pub get dartz

And you will have Dartz installed. 

Dartz has a special data type Either. Either takes two types of return type of data, one is for catching exception (failure) and other one is for success. Before I go further, let me give you an example of a situation. 

Here we created a class, and this class creates user and get users from the server. Since this is an abstract class, this would be implemented by other class. In general this abstract classes would be in domain layer and implementation would be in data layer.

BLoC Clean Architecture and TDD

Here I have two methods, one is createUser() and the other one is getUser(). Each of them will talk with server and return us a response.Whether the response is failure or success how do we know?

Dart's new feature record made it possible to have two data types to be defined when a function returns. Our failure and success could be mentioned at the same time using Dart's new feature.

This is amazing how dart deal with Exception inserted in Future. The left side is used to catch error or failure or exception. The right side is for success.

The above is still not Dartz. We can use Either type of Dartz to wrap our exception and success.

See how we wrap Exception inside Either.

Since we want to focus on clean architecture, we need to separate our exceptions. We may go ahead and create class in inside lib/core/errors/ folder. The file name would be failure.dart

Here we created a Failure class instead of Dart Exception class. We want to use our custom error type which will contain a message and statusCode.

Since our error or statusCode would be comming from server, we created a sub class name ApiFailure. Now let's use this Failure class for our repository class.

Now inside Either class we pass our generic data type Failure. Now we may also seperate Future<Either<Failure, void>> and Future<Either<Failure, List<User>>> in a separate file to be more cleaner.

We may create a typedef to do it. We may create a separate file lib/core/utils/typedef.dart

typedef ResultFuture = Future<Either<Failure, List<User>>>;

Now in the above code we just return List<User> on the right side. But we need to make a generic type since we may return anything on the right side, like we have seen may return void type as well.

So the above line change to 

typedef ResultFuture<T> = Future<Either<Failure, T>>;

We may also create one more void

typedef ResultVoid = ResultFuture<void>;

Now, let's go ahead and use the typedef in our repository.


Add Reviews