EN VI

Android - How to get success or error data without folding the response while using fpdart in flutter?

2024-03-12 02:30:04
Android - How to get success or error data without folding the response while using fpdart in flutter?

I'm using fpdart for catching errors in my flutter app. I wanted to get error message or success message directly without folding the whole response. There is getRight() and getLeft() method on res object but it returns Option<Success Data Type> and Option<Error Data Type> respectively. How could i extract the data directly without folding?

Future<Either<String, int>> getData() async {
  try {
    int data = await Future.delayed(Duration(seconds: 3), () => 15);
    return right(data);
   } catch (err) {
    return left(err.toString());
  }
 }

Solution:

I mostly create extension for this.

extension EitherExt on Either {
  ///! use only after checking the type
  get asLeft => (this as Left).value;
  get asRight => (this as Right).value;
}

And you can use like

final result = await getData(); 
///prefer checking `result.isRight()` on toplevel
final myInt = result.asRight;
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login