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

53 Views Asked by At

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());
  }
 }
1

There are 1 best solutions below

2
Md. Yeasin Sheikh On BEST ANSWER

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;