You need to enable JavaScript to run this app. 如何正确为Future<Either>类型的返回值使用fold方法?
优惠活动
大模型
产品
解决方案
定价
更多

如何正确为Future<Either>类型的返回值使用fold方法?

问题原因

userRegister 方法的返回类型为 Future<Either<Exceptions, bool>>,fold 是 Either 类的成员方法,不属于 Future 类,因此你无法直接在 Future 实例上调用 fold 方法,必须先等待异步执行完成,拿到 Future 包裹的 Either 实例后才可调用。

解决方法

方案1(推荐):使用await关键字异步等待

给userRegister的调用添加await关键字,同时确保承载该逻辑的方法被标记为async:

// 调用的函数需要标记async,返回值为Future包裹的状态类型
Future<UserState> yourHandlerFunction(UserEvent event) async {
  final failedOrResult = await _mourdakRepository.userRegister(event.formData);

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

方案2:使用Future.then链式调用

如果你不需要中断当前函数执行等待结果,也可以通过then方法在Future完成回调中处理Either:

return _mourdakRepository.userRegister(event.formData).then(
  (eitherValue) => eitherValue.fold(
    (exception) => UserExceptionState(exception.message),
    (isSuccesed) => UserRegisterState(isSuccesed)
  )
);

内容的提问来源于stack exchange,提问作者amin jamali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 01:06:03