flutter - 从 Future Either 方法调用两个方法,两者都具有 Future Either 返回类型
问题描述
我有这两种方法:
Future<Either<Failure, WorkEntity>> getWorkEntity({int id})
和
Future<Either<Failure, WorkEntity>> updateWorkEntity({int id, DateTime executed})
它们都经过测试并按预期工作。然后我有结合两者的第三种方法:
Future<Either<Failure, WorkEntity>> call(Params params) async {
final workEntityEither = await repository.getWorkEntity(id: params.id);
return await workEntityEither.fold((failure) => Left(failure), (workEntity) => repository.updateWorkEntity(id: workEntity.id, executed: DateTime.now()));
}
这个方法不起作用,它总是返回null。我怀疑这是因为我不知道在折叠方法中返回什么。如何使它起作用?
谢谢索伦_
解决方案
该fold
方法的签名如下:
fold<B>(B ifLeft(L l), B ifRight(R r)) → B
您的ifLeft
“Left(failure)”返回一个Either<Failure, WorkEntity>
但ifRight
“repository.updateWorkEntity(id:workEntity.id,执行:DateTime.now())”返回一个Future
。
最简单的解决方案是,如下所述:How to extract Left or Right from either type in Dart (Dartz)
Future<Either<Failure, WorkEntity>> call(Params params) async {
final workEntityEither = await repository.getWorkEntity(id: params.id);
if (workEntityEither.isRight()) {
// await is not needed here
return repository.updateWorkEntity(id: workEntityEither.getOrElse(null).id, executed: DateTime.now());
}
return Left(workEntityEither);
}
这也可能有效(也未经测试):
return workEntityEither.fold((failure) async => Left(failure), (workEntity) => repository.updateWorkEntity(id: workEntity.id, executed: DateTime.now()));
由于我看不到返回异常有任何好处,我只会抛出异常并用try/catch
块捕获它。
推荐阅读
- firebase - flutterfirebasecoreplugin-java-uses-or-overrides-a-deprecated-api 错误与最新的颤振版本 2.2.0 和最新的 API
- hibernate - Hibernate 中的错误:必须在调用 save() 之前手动分配此类的 ID:Model.Product at org.hibernate.id.Assigned.generate
- selenium - 如何将 chromedriver 添加到我的 github 存储库
- swift - Main.storyboard/Controller 和 searchBar 中的问题接线委托
- powerbi - Power BI DAX 查找特定时间段内的数据
- html - 如何使用谷歌脚本更改单元格中的值?
- python - 在 OpenCV 中实现加权平均绝对/平方差
- activerecord - Rails 6、ActiveRecord 和 Mysql 8,如何将字符串字段的长度设置为 512 个字符?
- c# - Topshelf.HostconfigurationException:服务未正确配置:
- node.js - 函数将对象作为 promise { pending } 返回