Boosting Flutter Error Handling: A Deep Dive into the Dartz Package and the Either Concept

Ibrahim Aboelyazed
4 min readNov 13, 2023

--

Error handling is one of the most important aspects of any project that you should implement and handle well, and in Flutter with Dart, it doesn’t have to be a maze of nested conditionals. Discover the power of the dartz package and the Either concept to unlock a clearer, more concise way to manage success and failure scenarios in your Flutter Applications, let’s have a deep dive into Either package and its concepts.

What is Either?

Either is like a container for a value that might be an error or -either- any other value. In this case, Left is the error and Right is the value respectively.

How can we use it?

Dart doesn’t support Functional Programming out of the box,
But using a package like dartz can achieve this for us.

Let’s have a look at a function that makes an API Request to get data and handles errors in a traditional way and then we will convert it to a more robust function that uses Either concept.

// A function that uses traditional error handling
Future<http.Response> getData() async {
try {
final response = await http.post(Uri.parse('yourapilink'), body: {});

if (response.statusCode == 200) {
return response; // Success case
} else {
// Failure case
switch (response.statusCode) {
case 400:
throw 'The server cannot process your request';
case 401:
throw 'You are Unauthorized';
default:
throw 'Something went wrong...';
}
}
} catch (e) {
// Catch unexpected errors
throw 'An unexpected error occurred: $e';
}
}

Despite the familiarity and structured control flow it offers, traditional exception handling can introduce performance overhead, disrupt the natural code flow, result in verbosity, and provide limited information, challenging developers to balance readability and efficiency

Now let’s convert this function to a more robust one that uses Either for error handling, With Either our function will look like this.

// Function that handles error with Either concept
Future<Either<String, http.Response>> getData() async {
try {
final response = await http.post(Uri.parse('yourapilink'), body: {});
if (response.statusCode == 200) {
// In this case the request is successful
// and we return Right containing the response
return Right(response);
}
// In this case the request wasn't successful
// and we can check status code
// to return a corresponding message
switch (response.statusCode) {
case 400:
return const Left('The server cannot process your request');
case 401:
return const Left('You are Unauthorized');
default:
return const Left('Something went wrong...');
}
} catch (e) {
return Left(e.toString());
}
}

Next, leveraging the Either concept, we can effectively handle potential errors and seamlessly integrate this function into various parts of your code. This approach allows for a more robust and flexible programming experience, we will deep deeper into how we can use it to how to handle the results of the function.

Handling function results using Fold

Using fold we can access the returned data from our function,
in case the request is successful the function will return the Right value which is the response and if not, the function will return the Left value which is a String representing an error message.

So our new function that uses the getData() function will look like this

Future initializeData() async {
// First we execute the getData() function and wait for the results.
final value = await getData();
// Then we fold the result for accessing the left and right value
// In case it is left (error) we will handle the error
// And in case it is right (the actual data) we will handle it accordingly.
value.fold(
(left) {
// Show an error message to the user
debugPrint(left);
},
(right) {
// The value returned in case the request was successful
// Use this data to update UI
debugPrint(right);
},
);
}

By incorporating this approach, the risk of overlooking error handling diminishes, making your project stronger and more robust, there are lots of neat features and things to discover more in the dartz package.

In conclusion, embracing Either concept in Flutter provides a robust framework for error handling, offering a clear alternative to traditional exceptions. By integrating the fold method thoughtfully, you enhance readability and gain a powerful tool for managing success and failure scenarios. Whether handling network requests, asynchronous operations, or form validation, Dartz empowers developers to write better, more expressive, and user-friendly code.

If you found this helpful, give it a clap and share! Write your thoughts in the comments, and follow for more insights and tips in software programming.

Consider connecting with me on LinkedIn: https://www.linkedin.com/in/ibrahim-aboelyazed

--

--