I'm struggling to understand how to sum multiple objects in a list together matching certain conditions
I have :
List<TruckFruit> = truckFruits;
class TruckFruit extends Equatable {
final String fruitType;
final int shape;
final int availableCount;
final int totalCount;
TruckFruit({
required this.fruitType,
required this.shape,
required this.availableCount,
required this.totalCount,
});
@override
List<Object?> get props => [
shape,
fruitType,
availableCount,
totalCount,
];
}
I'd like to sum multiple TruckFruit inside this truckFruits list which have equal fruitType String && equal shape int
such as from this list :
final List<TruckFruit> truckFruits = [
TruckFruit(fruitType: 'Apple', shape: 4, availableCount: 1, totalCount: 10),
TruckFruit(
fruitType: 'Strawberry', shape: 4, availableCount: 2, totalCount: 6),
TruckFruit(fruitType: 'Apple', shape: 4, availableCount: 8, totalCount: 30),
TruckFruit(
fruitType: 'Strawberry', shape: 2, availableCount: 5, totalCount: 8),
];
I'd like to get this list :
final List<TruckFruit> newTruckFruitsList = [
TruckFruit(fruitType: 'Apple', shape: 4, availableCount: 9, totalCount: 40), // the availableCount & totalCount were summed from the two Apples with same shape
TruckFruit(
fruitType: 'Strawberry', shape: 4, availableCount: 2, totalCount: 6),
TruckFruit(
fruitType: 'Strawberry', shape: 2, availableCount: 5, totalCount: 8),
];