我有一段代码,如下所示:
final Either<Failure, Unit> resA = await deleteA();
resA.fold(
(failure) => handleFailure(),
(success) async {
final Either<Failure, Unit> resB = await deleteB();
resB.fold(
(failure) => handleFailure(),
(success) => handleSuccess(),
);
},
);
Run Code Online (Sandbox Code Playgroud)
基本上,我想调用第一个函数,它返回失败或单位(成功值并不重要)。
然后,如果第一个函数成功,我想调用另一个函数,它也返回 Future 或 Unit。
我该如何避免fold另一个内部的这种丑陋的嵌套调用fold?
我正在使用dartz包,它非常酷,但缺乏文档。
我所处的情况是与实体和模型一起工作。基本上我的实体描述了我的数据应该是什么样子,我的模型扩展了这些实体并有一个函数 toMap 将它们转换为 json 对象。
因此,我有 2 个实体:Car 和 Brand,其中 Car 属性之一是 Brand 类型。
class Car {
final String name;
final Brand brand;
const Car({
required this.name,
required this.brand,
});
}
class Brand {
final String label;
final String color;
const Brand({
required this.label,
required this.color,
});
}
Run Code Online (Sandbox Code Playgroud)
然后我有2个模型CarModel和BrandModel,分别扩展了Car和Brand。
class CarModel extends Car {
CarModel({
required String name,
required BrandModel brand,
}) : super(
name: name,
brand: brand,
);
Map<String, dynamic> toMap() {
return {
'name': name,
'brand': brand,
}; …Run Code Online (Sandbox Code Playgroud)