Flutter how to group a list from firebase based on a certain value

1,293

Actually fixing it was quite easy with the link to the question I firstly provided. You can just use a GroupedListView (package) instead of the Listview.builder. Don't know why it took me so long to get that :p Hopefully this helps someone else in the future :)

StreamBuilder(
   stream: Firestore.instance.collection('products').snapshots(),
   builder: (context, snapshot) {
     if (!snapshot.hasData) return const Text("Loading...");
     return GroupedListView(
       elements: snapshot.data.documents,
       groupBy: (element) => element['category'],
       groupSeparatorBuilder: _buildGroupSeparator,
       itemBuilder: buildProductItem,
       order: GroupedListOrder.ASC,
     );
   }
),```
Share:
1,293
HenkDeKipGaming
Author by

HenkDeKipGaming

Updated on December 02, 2022

Comments

  • HenkDeKipGaming
    HenkDeKipGaming over 1 year

    I have a firebase database with 2 relevant collections: "products" and "categories".

    I would like to show the products in a listview grouped by their category.

    In every product document there is a 'category' field which is the category id.

    Right now I have this code to just create the listview:

    StreamBuilder(
        stream: Firestore.instance.collection('products').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) return const Text("Loading...");
          return ListView.builder(
            itemBuilder: (context, index) => buildProductItem(context, snapshot.data.documents[index]),
            itemCount: (snapshot.data.documents.length),
          );
        }
    )
    

    I've tried a few things (like this: question), but I want to keep it within the StreamBuilder so the data will still update live.

    How would I group them so I can show a title above every group and the products corresponding to that title underneath?