如何正确为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
相关产品推荐
相关产品推荐

