如何通过变量对 Firestore 进行 Flutter 分组文档?

问题描述 投票:0回答:1

我需要对产品集合中的多个文档进行分组,但我找不到方法。我想按“颜色”对它们进行分组。我无法手动插入每种颜色,因为颜色取决于电子商务所有者并且总是会更改名称。 这是我的代码:

@override
  Widget build(BuildContext context, WidgetRef ref) {
    return Container(
      width: double.infinity,
      height: 400,
      child: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
          stream: FirebaseFirestore.instance.collection('products').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Text(
                'Caricamento...',
                style: TextStyle(color: Colors.white),
              );
            }
            if (snapshot.hasError) {
              print(snapshot.error.toString());
            }

            return ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: snapshot.data!.docs.length,
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (ctx, index) {
                  Map<String, dynamic> billo =
                      snapshot.data!.docs[index].data();
                  var newMap = groupBy(billo, (Map obj) => obj['release_date']);
                  print(newMap);

                  return Column(
                    children: [
                      CommonHomeHeader(
                        title: billo['color'],
                        onPressed: () {
                          ref.read(categoryIdProvider.notifier).state =
                              billo['id'];
                          context.push(RouteLocation.categoryDetails);
                        },
                      ),
                      CommonListView(
                        height: MediaQuery.of(context).size.height * 0.25,
                        itemCount: billo.length,
                        itemBuilder: (ctx, index) {
                          final product = billo[index];

                          return ProductoCard(product: product);
                        },
                      ),
                    ],
                  );
                });
          }),
    );
  }
}

我尝试分组依据和grouped_list,但它说我可以在可迭代映射动态中使用映射字符串动态

flutter firebase dart google-cloud-platform google-cloud-firestore
1个回答
0
投票

当您使用以下行代码时:

stream: FirebaseFirestore.instance.collection('products').snapshots()

这意味着您正在无序地阅读

products
集合中的所有文档。如果您想获取按特定字段排序的文档,那么您应该调用 Query#orderBy() 并传递要对文档进行排序的字段名称以及方向(升序或降序)。这样,您将获得按 color 排序的产品列表,例如:

stream: FirebaseFirestore.instance.collection('products').orderBy('color').snapshots()

这也意味着您不必在客户端上进行任何订购。

© www.soinside.com 2019 - 2024. All rights reserved.