Chad
Chad

Reputation: 685

Flutter Calculating the total price of the items in thier category

To-Do App

class ToDoItem{
  final String id;
  final String title;
  final Color color;
  final int price;
  final IconData icon;
  final String todoListId;

  const ToDoItem({
    @required this.color,
    @required this.id,
    @required this.todoListId,
    @required this.price,
    @required this.title,
    @required this.icon,
  });}

I am struggling to add up the total sum of items price in the to-Do lists that is equal to todoListId for example :

THE LISTS SCREEN

enter image description here

THE LISTS ITEMS SCREEN

enter image description here

so I am trying to calculate the Total Items Price

this is what I have tried:

  List<Map<String, Object>> get totalItemsPrice{
    return List.generate(1, (index) {
      var totalPriceSum = 0.0;
      for (var i = 0; i < toDo.length; i++) {
        totalPriceSum = toDo[index].amount + totalPriceSum ;
      }
      return {
        'price': totalSum,
      };
    }).toList();
  }

  double get totalPriceSum {
    return totalItemsPrice.fold(0.0, (sum, item) {
      return sum + item['price'];
    });
  }

the toDo looks like this:

List<ToDO> toDo= [];

But it is not working it is calculating the total price of all of the to-do items when I want it to only calculate the total price of the items that are in their category

Upvotes: 4

Views: 4148

Answers (2)

Trịnh Đức Duy
Trịnh Đức Duy

Reputation: 253

Let's see below code

double totalPriceSum() {
 return ItemsPrice.map((item) => item.price * item.quantity)
               .reduce((ele1, ele2) => ele1 + ele2); 
}

Upvotes: 0

Abion47
Abion47

Reputation: 24671

If you want to filter based on the item's todoListId then you will need to provide it to the method. From there, use a where before the fold to only sum items with the matching id:

double totalPriceSum(int todoListId) {
  return ItemsPrice.where((item) => item.todoListId == todoListId)
                   .fold(0.0, (sum, item) => sum + item['price']); 
}

Upvotes: 4

Related Questions