Why we should use option in flutter?

408

You can see that Option and Either provided by the dartz package are used a lot with apps following functional programming paradigm. They are called monads.

Let's take an example, when making an API call, it can either return an expected value, or an error. Usually we'll return null when an error happens or throw an Exception, but this might result in a Runtime Error, and not useful to handle different error types (to display the exact error message for the end-users).

Monad allows us to encapsulate both of these 2 outcomes by a generic class.

Coming back to Option, it represents a value of one of two possible types. The convention is to consider missing value as an instance of None and expected success value in an instance of Some. So it present the absent of the return value with a class and not just null

Moreover, you can use the fold() method to handle both cases like this:

void main() {
  final car = Car(Colors.black, 'Mercedes');

  final option = getNameAsOptional(car); // Get name of the car, returning an Option 

  // Use the fold() method to handle both case: name is None and name is Some
  option.fold(
    () => print('None!'), // 1st case: Failure
    (name) => print('Aha! Your car's name is $name'), // 2nd case: Success
  );
}

P/S: You can read more on monads in this article. It's from the author of a different package, but the base concept remains the same.

Share:
408
Amit Singh
Author by

Amit Singh

I m passionate Flutter and firebase developer. email: [email protected] whatsApp : +919548582776 Feel free to reach out me if you have any query.

Updated on December 28, 2022

Comments