Nestor Ariza
Nestor Ariza

Reputation: 69

How can I know what is the most sold product of a list? flutter-dart

I have a list of items from the orders by date, so based on its quantity I want to find what is the most sold product.

This is the class for my items

class CartItem{
  String id;
  String name;
  String image;
  int quantity;
  double price;

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

For example:

List<CartItem> list = orders.products;

list.forEach((element => print('${element.name} : ${element.quantity)');

It will print:

Dress : 1
Boots : 2
Trousers : 3
Dress : 2
Trousers : 2

So based on this example, how can I get the most sold product which is 'Trousers' and the sum of its quantity which is 5 for this case.

Thank you in advance.

Upvotes: 0

Views: 409

Answers (2)

thusith.92
thusith.92

Reputation: 306

You can covert the list to a map so you can see distinct items in the list. but rather than assigning the value to the key, if the key already exists, add the value

as:

list.forEach((item) => {
  map2[item.name] = item.quantity + (map2[item.name] ?? 0)
});

you will get the output:

{Dress: 3, Boots: 2, Trousers: 5}

then finally you can sort the map like this:

var sortedKeys = map2.keys.toList(growable:false)
    ..sort((k1, k2) => map2[k2].compareTo(map2[k1]));
    LinkedHashMap sortedMap = new LinkedHashMap
      .fromIterable(sortedKeys, key: (k) => k, value: (k) => map2[k]);
  print(sortedMap);

sorting os mentioned here as well How to sort map value?

then you can get the first element which is the product with the highest orders

hope this helps

Upvotes: 1

Ketan Ramteke
Ketan Ramteke

Reputation: 10675

Here is another example:

// Dart 2.6.1 

main() {
  List list = [
    {
      "name":"Dress",
      "quantity" : 1
    },{
      "name":"Boots",
      "quantity" : 2
    },{
      "name":"Trousers",
      "quantity" : 3
    },{
      "name":"Dress",
      "quantity" : 2
    },{
      "name":"Trousers",
      "quantity" : 2
    }
  ];


  var products={

  };

  String mostSelling="";
  int quantity=0;

  list.forEach((e) {

    if(products[e["name"]]== null){
      products[e["name"]]= e["quantity"];
    } else {
     products[e["name"]]+= e["quantity"];
    }

    if(products[e["name"]] >quantity){
      mostSelling=  e["name"];
      quantity = products[e["name"]];
      }
   }
  );


  print("$mostSelling : $quantity");
}

Output:

enter image description here

Upvotes: 0

Related Questions