Aman Kataria
Aman Kataria

Reputation: 616

(Flutter) Displaying data of a List in different groups in UI

I have a list (which is from a database table) like this: (Note: I have already de-serialized the List)

groupNo | Sales
---------------
  1        5
  1        1  
  1        3
  2        6  
  2        9  
  2        2
  2        1  
  3        8  
  3        3  
  4        4  
  4        1  
  4        6  
  4        0  
  4        4  
  4        1  

Now I want to display this data like this: enter image description here

What's the best way of displaying this in the UI?

Upvotes: 0

Views: 3097

Answers (2)

user7418129
user7418129

Reputation: 1114

(I know I'm too late. But let this solution will definitely help others)

It's a simple thing because Flutter Pub.dev just introduced a Library called => grouped_list. Just go through this link. https://pub.dev/packages/grouped_list#-example-tab- Cause this made my day and it is gonna help you too. Enjoy Flutter

Upvotes: 0

Aman Kataria
Aman Kataria

Reputation: 616

Lets say the List is called itemList

First we need a list for number of groups. Since group number is repeated in the itemList, using it directly to build cards for each group won't work. So we can add all groupNo from itemList to a Set(Since a Set will remove all duplicate values).

We first declare a Set

Set groupSet = Set();

After that we create a readGroup() function which will be declared in initState

readGroup() {
  setState((){  
   itemList.forEach((item){
     groupSet.add(item.groupNo);
     });
    });
   }

Now we will use ListView.builder to create a card for each group. Inside the builder, we will use the for loop to populate items of each group in their respective cards.

Note: We don't use group number from Set since the order of item in Set is not guaranteed. Thus instead we use index + 1.

ListView.builder(
 itemCount: groupSet.length,
 itemBuilder: (context, index) {
   return Column( children:<Widget>[
   Text("Group "+ (index + 1).toString()),
    SizedBox(height:10),
     Row(children: <Widget>[
      for(item in List) if(item.groupNo = index + 1)  
       Text(item.sales)
       ]);
      ]);
     }
   );

Upvotes: 2

Related Questions