flutterfuturedartz

How to use the fold method for a future type?


I have this method as my repository:

Future<Either<Exceptions, bool>> userRegister(FormData formData) async {
    try {
      final response = await _mourdakApi.userRegister(formData);
      bool _isSuccesed;
      if (response.statusCode == 200)
        _isSuccesed = true;
      else
        _isSuccesed = false;
      return Right(_isSuccesed);
    } catch (e) {
      return Left(
        Exceptions(
          message: e.toString(),
        ),
      );
    }
  }

Now I want to use fold method here:

final failedOrResult = _mourdakRepository.userRegister(event.formData);

return failedOrResult.fold(
      (exception) => UserExceptionState(exception.message),
      (isSuccesed) => UserRegisterState(isSuccesed));

But I got this error:

The method 'fold' isn't defined for the type 'Future'

Solution

  • I don't know if it hasn't already solved, but only the await is missing. Another way would be to use the Task method, defined in lib dartz

    final failedOrResult = await _mourdakRepository.userRegister(event.formData);
    
    return failedOrResult.fold(
          (exception) => UserExceptionState(exception.message),
          (isSuccesed) => UserRegisterState(isSuccesed));