尝试在 Future<List> 上使用数组方法 "fold" 来获取项目的总价
Trying to use array method "fold" on a Future<List> to get total price of items
在 Dart/Flutter 中,我正在构建一个模型,在该模型中,我使用 Future 和异步等待从远程端点获取所有产品。
当我检索到列表时,我想指定一个 属性 returns 使用 Dart 列表的 "fold" 方法的所有项目的总量。
像这样:
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;
})
);
但是我得到一个错误:
The operator '+' isn't defined for the class 'FutureOr'. Try
defining the operator '+'.dart(undefined_operator).
我该如何用异步语言解决这个问题?
谢谢
您的代码的问题是 await
不适用于 items
但适用于所有表达式 items.then(...
.
以下代码应该有效:
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);
};
在 Dart/Flutter 中,我正在构建一个模型,在该模型中,我使用 Future 和异步等待从远程端点获取所有产品。
当我检索到列表时,我想指定一个 属性 returns 使用 Dart 列表的 "fold" 方法的所有项目的总量。
像这样:
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;
})
);
但是我得到一个错误:
The operator '+' isn't defined for the class 'FutureOr'. Try defining the operator '+'.dart(undefined_operator).
我该如何用异步语言解决这个问题?
谢谢
您的代码的问题是 await
不适用于 items
但适用于所有表达式 items.then(...
.
以下代码应该有效:
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);
};