PaperChimney
PaperChimney

Reputation: 21

Flutter, trying to use a getter to sum up elements in a map

I have a map of CartItems which each contain an id, title, quantity, and price. I currently have a getter (itemCount) which returns the number of CartItems. But I would instead like the getter to return the sum of the quantities of all the CartItems in the map. Below is the relevant code snippet

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({this.id, this.title, this.quantity, this.price});
}

class Cart with ChangeNotifier {
  Map<String, CartItem> items = {};

  int get itemCount {
    return items.length;
  }

Upvotes: 2

Views: 962

Answers (1)

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9900

Just loop through map items and calculate the sum of quantities

using reduce

  int get itemCount {
    return items.values
        .map((item) => item.quantity)
        .reduce((count, quantity) => count + quantity);
  }

using forEach

int get itemCount {
    int count =0;
    items.values.forEach((item) => count+=item.quantity);
    return count;
  }

using add / remove / update methods,

If you are use this method frequently, you can create add,remove methods on Cart class and calculate the total quantity sum only when adding and removing items.This way you don't need to run the loop each time and i prefer this way.

Upvotes: 1

Related Questions