Dart:如何减少类列表

fre*_*n29 4 dart

我想减少类列表,例如:

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);
}
Run Code Online (Sandbox Code Playgroud)

但它会引发错误

错误:无法将“double”类型的值分配给“Product”类型的变量。

jul*_*101 9

reduce 方法的语法指定为:

reduce(E combine(E value, E element)) ? E
Run Code Online (Sandbox Code Playgroud)

所以该方法应该返回与两个输入相同的类型。在您的情况下, curr 和 next 值属于 Product 类型,但您返回的是 double 值。

你真正想要使用的是 fold 方法:

fold<T>(T initialValue, T combine(T previousValue, E element)) ? T
Run Code Online (Sandbox Code Playgroud)

所以你的代码是:

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.fold(0, (sum, next) => sum + next.price);
  print(sum);
}
Run Code Online (Sandbox Code Playgroud)