Home > front end >  Flutter Group items in a ListViewBuilder and Count Total
Flutter Group items in a ListViewBuilder and Count Total

Time:07-11

I have a Product class that contains many properties include the name property,

final List<Product> listViewProductsRecordList = snapshot.data;

I have a list view builder which I use to display each product

 ListView.builder(
     padding: EdgeInsets.zero,
     scrollDirection: Axis.horizontal,
     itemCount: listViewProductsRecordList.length,
     itemBuilder: (context, listViewIndex) {
      final listViewProductsRecord = listViewProductsRecordList[listViewIndex];
     return Text("${listViewProductsRecord.location.name}");

I get the correct output:

location1
location2
e.t.c

Here come where I am stuck in implementation, I want to display something like this:

location1: 20 Products
location2: 30 Products

What I have tried is the following:

final Map<String,Product> cities = {};
listViewProductsRecord.forEach(
    product=> 
      if(product.location.name==product.location.name){
         cities[product.location.city] = product;
      }
);

Now I don't know how to proceed from here to achieve the output above without external packages.

#Update

Here is my Product class

class Product {
    Product({
        this.id,
        this.name,
        this.description,
        this.location,
    });

    final String id;
    final String name;
    final String description;
    final Location location;
}

CodePudding user response:

try changing the Text widget to this :

Text("${listViewProductsRecord.location.name}:${listViewProductsRecord.length}" );

CodePudding user response:

Okay i managed to solve it and the following is the solution i used for anyone with a similar problem

List<Product> listViewProductsRecordList = snapshot.data;
   // group the products by city
      Map<String, List<Product>> cityProducts = {};
      for (Product product in listViewProductsRecordList) {
         if (cityProducts[product.location.city] == null) {
            cityProducts[product.location.city] = [];
         }
          cityProducts[product.location.city].add(product);
       }
       return ListView.builder(
            padding: EdgeInsets.zero,
            scrollDirection: Axis.horizontal,
            itemCount: cityProducts.length,
            itemBuilder: (context, listViewIndex) {
            final listViewProductsRecord =
            listViewProductsRecordList[listViewIndex];

     return Text("${cityProducts.keys.toList([listViewIndex]}/${cityProducts.values.toList([listViewIndex].length}");
         },);
  • Related