Firestore 中的自动更新颤振查询结果 [英] Auto update flutter query results in firestore

查看:36
本文介绍了Firestore 中的自动更新颤振查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉 Flutter 基础知识,也了解流构建器.但是,如何在检测到更改时更新我的​​查询结果.
这是我想在文档发生更改时自动更新的代码

I am familiar with flutter basics and I know about stream builders. However how do I update my query results when it detects a change.
Here is the code I would like to auto update when there is a change to the document

 void initState() {
    getUsers();
    super.initState();
  }

  getUsers() async {
    final FirebaseAuth auth = FirebaseAuth.instance;
    final User? user = auth.currentUser;
    final uid = user!.uid;
    final QuerySnapshot snapshot =
        await userRef.where('uid', isEqualTo: uid).get();
    snapshot.docs.forEach((doc) {
      name = doc["firstName"];
      children = doc["children"].toString();
      print(doc["children"].toString());
    });
  }

这段代码效果很好,但是当我改变孩子的数量时,除非我重新启动应用程序,当然,用户不能这样做
这是我的 firestore 收藏的图片
firestore 集合的图片
如您所见,此查询在整个集合中搜索与当前用户 uid 具有相同 uid 的文档.这就是我检索特定于用户的数据的方式,例如名字和姓氏以及孩子.我有一个允许用户添加孩子的功能,但是,孩子的数量保持不变,直到我重新启动应用程序.在子项数量发生变化后,如何使结果自动更新.
谢谢!

This code works great, however when I change the number of children for instance, unless I restart the app, which of course, the user can not do
Here is an image of my firestore collection
Image of firestore collection
As you can see, this query searches the entire collection for a document with the same uid as the current users uid. This is how I retrieve data specific to a user, like first and last name and children. I have a functionality that allows the user to add children, however, the number of children stays the same until I restart the app. How can I make the results auto update after then number of children changes.
Thanks!

推荐答案

调用 get() 意味着您的应用程序 从数据库中读取一次文档,然后停止关注.

Calling get() means that your application reads the documents from the database once, and then stops caring.

如果您想从数据库获取实时更新,如果基础数据更改,您需要使用 snapshots 属性,它为您提供Stream 更新.

If you want to get realtime updates from the database if the underlying data changes, you'll need to use the snapshots property, which gives you a Stream of updates.

要在 UI 中显示更新流,您可以使用 StreamBuilder,如 实时更改.

To show that stream of updates in the UI, you'd use a StreamBuilder as shown in the FlutterFire documentation on realtime changes.

这篇关于Firestore 中的自动更新颤振查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆