例如,我要减少类列表:
class Product {
final String name;
final double price;
Product({this.name, this.price});
}
List<Product> products = [
Product(name: 'prod1', price: 100.0),
Product(name: 'prod2', price: 300.0),
];
void main() {
var sum = products.reduce((curr, next) => curr.price + next.price);
print(sum);
}
但是会引发错误
错误:不能将类型为'double'的值赋给'产品'类型的变量。
答案 0 :(得分:3)
reduce方法的语法指定为:
RadGrid
因此,该方法应返回与两个输入相同的类型。在这种情况下,curr和next值的类型为Product,但返回的是double值。
您正确想使用的是fold方法:
BatchEdit
所以您的代码应该是:
RadMaskedTextbox
答案 1 :(得分:1)
您也可以使用
var sum = products.map((product) => product.price).reduce((v, e) => v + e);
print ("$sum"); // prints 400.0