【问题标题】:Flutter: Streambuilder for documents from queryFlutter:用于查询文档的 Streambuilder
【发布时间】:2021-10-22 22:23:22
【问题描述】:

如何获取从查询快照返回的所有项目的列表视图?

FirebaseFirestore.instance
        .collection("children")
        .where("parentUID", isEqualTo: uid)
        .snapshots()
        .listen((result) {
      result.docs.forEach((result) {
        setState(() {
          childFirstName = result["childFirstName"];
          childLastName = result["childLastName"];
          points = result["points"];
          docID = result.id;
          print('$docID');
        });
      });
    });
  }

这就是我能想到的,这是数据库的图像,
Image of database

如何创建一个列表视图,为每个文档创建一个项目,其中 parentUID 等于当前用户 uid,该用户已存储在变量 uid

【问题讨论】:

  • 您共享的代码有什么问题?如果您不确定如何在列表视图中显示这些文档,请查看此文档:firebase.flutter.dev/docs/firestore/usage#realtime-changes
  • 我不知道从哪里开始
  • 我想创建一个查询并从结果中制作一个流,制作一个列表视图并将每个结果放入一个项目中
  • 这正是节目中的做法。它创建一个_usersStream = FirebaseFirestore.instance.collection('users').snapshots(),您可以用您的查询替换它,然后在StreamBuilder 中使用它。您是否尝试让该示例在您自己的代码中运行?
  • 我不想要集合中所有文档的流,但集合 children 中的文档具有 parentUID 匹配(等于)当前用户 ID,我存储在一个名为 uid 的变量

标签: firebase flutter google-cloud-firestore


【解决方案1】:

您可以使用下面的示例代码。 它展示了如何使用查询中的流并返回一个ListView.builder,它在ListTile 中显示信息。

StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
  stream: FirebaseFirestore.instance
    .collection('children')
    .where('parentUID', isEqualTo: uid)
    .snapshots(),
  builder: (BuildContext context, snapshot) {
    if (snapshot.data == null) {
      return Center(child: CircularProgressIndicator());
    } else {
      final List<QueryDocumentSnapshot<Map<String, dynamic>>> docs = snapshot.data!.docs;

      return ListView.builder(
        itemCount: docs.length,
        itemBuilder: (_, index) {
          final doc = docs[index];
          final childFirstName = doc["childFirstName"];
          final childLastName = doc["childLastName"];
          final points = doc["points"];
          final docID = doc.id;

          return ListTile(
            title: Text('$childFirstName $childLastName'),
            subtitle: Text(points),
          );
        },
      );
    }
  },
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 2020-12-02
    • 2021-12-06
    • 2021-08-17
    • 2020-08-11
    • 2019-03-09
    • 2021-10-15
    • 2022-01-16
    相关资源
    最近更新 更多