I want to reduce a list of classes for example:
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);
}
but it throws an error
Error: A value of type 'double' can't be assigned to a variable of type 'Product'.
The syntax for the reduce method are specified as:
reduce(E combine(E value, E element)) → E
So the method should return the same type as the two input. In you case the curr and next values are of the type Product but your are returning a double value.
What you properly want to use are instead the fold method:
fold<T>(T initialValue, T combine(T previousValue, E element)) → T
So you code would be:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With