List “尝试使用数组方法”;“折叠”;关于未来<;列表>;获取项目的总价
在Dart/Flatter中,我正在构建一个模型,在该模型中,我使用Future和async Wait从远程端点获取所有产品 检索列表后,我希望指定一个属性,该属性使用省道列表的“折叠”方法返回所有项目的总量 大概是这样的:List “尝试使用数组方法”;“折叠”;关于未来<;列表>;获取项目的总价,list,asynchronous,flutter,dart,future,List,Asynchronous,Flutter,Dart,Future,在Dart/Flatter中,我正在构建一个模型,在该模型中,我使用Future和async Wait从远程端点获取所有产品 检索列表后,我希望指定一个属性,该属性使用省道列表的“折叠”方法返回所有项目的总量 大概是这样的: Future<List<Product>> get items async => // here i get products await Future.wait(_itemIds.map((id) => api.getProduct
Future<List<Product>> get items async => // here i get products
await Future.wait(_itemIds.map((id) => api.getProduct(id)));
Future<int> get totalPrice async => // here i calculate products total amount
await items.then((iii) => iii.fold(0, (total, current) async {
return total + current.price;
})
);
Future-get-items-async=>//这里是我的产品
wait Future.wait(_itemIds.map((id)=>api.getProduct(id));
Future get totalPrice async=>//这里我计算产品总额
等待项。然后((iii)=>iii.fold(0,(总计,当前)异步{
返回总计+当前价格;
})
);
但我有一个错误:
未为类“FutureOr”定义运算符“+”。尝试
定义运算符“+”.dart(未定义的_运算符)
我应该如何用异步语言解决这个问题
谢谢您的代码的问题是,
await
不适用于项
而是适用于所有表达式项。然后(…
)
以下代码应该可以工作:
Future<List<Product>> get items async => // here i get products
await Future.wait(_itemIds.map((id) => api.getProduct(id)));
Future<int> get totalPrice async { // here i calculate products total amount
final products = await items;
return products.fold<int>(0, (total, current) => total + current.price);
};
Future-get-items-async=>//这里是我的产品
wait Future.wait(_itemIds.map((id)=>api.getProduct(id));
Future get totalPrice async{//这里我计算产品总额
最终产品=待处理项目;
退货产品。折数(0,(总计,当前)=>总计+当前价格);
};
您也可以执行返回(等待项目)。折叠(0,(总计,当前)=>总计+当前。价格);
。我通常这样做是为了避免创建另一个变量。谢谢,但两者仍然返回相同的编译器错误:没有为类“FutureOr”定义运算符“+”。请尝试定义运算符“+”。代码已更新。我认为问题来自此异步函数中对折叠类型参数的错误推断。是的,强制转换折叠方法可以解决问题问题。感谢dart编译器仍然返回相同的错误:未为类“Product”定义运算符“+”。请尝试定义运算符“+”。dart(未定义的_运算符)