firebase 在StreamBuilder flutter中使用分组列表视图

ht4b089n  于 2022-12-30  发布在  Flutter
关注(0)|答案(1)|浏览(169)

我的收藏中有文档,有2个字段。(字符串注解,Int日期),
日期类型为int,因为它是这样发送的:第一个月
我想使用时间对项目进行分组,如下图所示

在此之前,我使用ListView.Builder来列出项目。它工作起来没有问题。(下面的代码)

StreamBuilder(
      stream: _FirebaseDB,
      builder: ((context, AsyncSnapshot snapshot) {
        return snapshot.hasData
            ? ListView.builder(
                  itemCount: snapshot.data.docs.length,
                  itemBuilder: (context, index) {
                    return Text(
                      snapshot.data.docs[index]["note"],
                    );
                  },
                ),
            : Container();
      }),
    );

我想对条目进行分组。所以我使用了grouped_list: ^5.1.2包并将代码更改为:

StreamBuilder(
      stream: _FirebaseDB,
      builder: ((context, AsyncSnapshot snapshot) {
        return snapshot.hasData
            ? Container(
                padding: const EdgeInsets.symmetric(vertical: 5),
                child: GroupedListView(
                  elements: [snapshot.data.docs],
                  groupBy: snapshot.data.docs["time"],
                  groupHeaderBuilder: (element) => Text("Group"),
                  itemBuilder: (context, element) {
                    return Card(
                      elevation: 8,
                      child: Text(snapshot.data.docs["note"]),
                    );
                  },
                )
                )
            : Container();
      }),
    );

它不工作。它显示如下错误:

类型“String”不是“index”的类型“int”的子类型

The following _TypeError was thrown building StreamBuilder<QuerySnapshot<Map<String,
dynamic>>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Map<String, 
dynamic>>, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>>>#63cd8):
hc8w905p

hc8w905p1#

用这个解决了

StreamBuilder(
        stream: _FirebaseDB,
        builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
          if (!streamSnapshot.hasData) return const Text("Loading...");
          return GroupedListView<dynamic, String>(
            elements: streamSnapshot.data!.docs,
            groupBy: (element) =>
            element['time'],
            groupSeparatorBuilder: (String value) => Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                value,
                textAlign: TextAlign.center,
                style:
                    const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
            ),
            useStickyGroupSeparators: true,
            floatingHeader: true,
            order: GroupedListOrder.ASC,
            itemBuilder: (context, dynamic element) {
              return Card(
                margin: const EdgeInsets.all(5),
                child: ListTile(
                  title: Text(element['note']),
                ),
              );
            },
          );
        });

相关问题