Warm tip: This article is reproduced from stackoverflow.com, please click
dart flutter

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

发布于 2020-03-27 10:26:23

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?

Questioner
Aman Kataria
Viewed
118
Aman Kataria 2019-07-03 22:57

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)
       ]);
      ]);
     }
   );