繁体   English   中英

Firestore/Flutter:遍历文档集合的 ID 和 output 它们作为列表

[英]Firestore/Flutter: Iterating through the ID of a collection of documents and output them as a list

我想编写一个代码,输出文档中每个文档的文档 ID,该文档位于StreamBuilder订阅的集合中。

我的 Firestore 结构是这样的:

  • 2020-2021(收藏)
    • 我的班级(文档)
      • 分数(集合)
        • 测验 1(这些是文档的文档 ID)
        • 测验 2
        • 测验 3

我的代码可能看起来很复杂,但简而言之,我想要实现的是 output 将集合(分数)中所有文档的文档 ID 放入列表中,而StreamBuilder订阅了文档收集的更改(MyClass ) 集合。 但是,它给了我这个错误: NoSuchMethodError: 'doc', method not found, Receiver: null, Arguments:[]我想我有一个语法错误,但我不知道如何纠正它。 我也不确定使用map方法是否正确。

    classname = "MyClass";
    CollectionReference schoolYear =
      FirebaseFirestore.instance.collection("2020-2021");
    
    Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(30),
      child: StreamBuilder(
        builder: (context, streamSnapshot) {
          return SingleChildScrollView(
            child: DataTable(
              columns: streamSnapshot.data.doc.map((DocumentSnapshot document) {
                return new DataColumn(label: Text(document.id));
              }).toList(),
              rows: <DataRow>[],
            ),
          );
        },
        stream: schoolYear.doc(classname).snapshots(),
      ),
    );
  }

这是完整的错误日志(更改为 Thavamani 的代码后): 错误日志

您当前的侦听schoolYear.doc(classname).snapshots()侦听对文档MyClass所做的更改,并且它不携带它的子集合Scores详细信息。

要获取Scores集合中的所有文档 ID,您可以使用 stream/future 来获取集合中可用的所有文档。

例如,stream 构建器方式

Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(30),
      child: StreamBuilder(
        builder: (context, streamSnapshot) {
           if (streamSnapshot.hasError) {
              // print() you could check errors here
              return Icon(
                Icons.error_outline,
                color: Colors.red,
                size: 60,
              );
           } else if (streamSnapshot.hasData) {
               return SingleChildScrollView(
                  child: DataTable(
                  columns: streamSnapshot.data.docs.map((DocumentSnapshot document) {
                  return new DataColumn(label: Text(document.documentID));
                 }).toList(),
                rows: <DataRow>[],
              ),
            );
          } else {
            return SizedBox(
                 child: const CircularProgressIndicator(),
                 width: 60,
                 height: 60,
            );
        }
        stream: schoolYear.doc(classname).collection('Scores').snapshots(),
      ),
    );
  }
  • 如果您不想收听文档,只需 go 和未来的构建器使用collection('Scores').getDocuments()而不是collection('Scores').snapshots()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM