如何使用 Flutter 侦听 Cloud Firestore 中的文档更改? [英] How to listen for document changes in Cloud Firestore using Flutter?

查看:24
本文介绍了如何使用 Flutter 侦听 Cloud Firestore 中的文档更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个侦听器方法,用于在发生更改时检查文档集合的更改.

I would like to have a listener method that checks for changes to a collection of documents if changes occur.

类似于:

import 'package:cloud_firestore/cloud_firestore.dart';


  Future<Null> checkFocChanges() async {
    Firestore.instance.runTransaction((Transaction tx) async {
      CollectionReference reference = Firestore.instance.collection('planets');
      reference.onSnapshot.listen((querySnapshot) {
        querySnapshot.docChanges.forEach((change) {
          // Do something with change
        });
      });
    });
  }

这里的错误是 onSnapshot 没有在 CollectionReference 上定义.

The error here is that onSnapshot isn't defined on CollectionReference.

有什么想法吗?

推荐答案

通读 cloud_firestore的文档你可以看到一个QueryStream可以通过snapshots()获得.

Reading through cloud_firestore's documentation you can see that a Stream from a Query can be obtained via snapshots().

为了让您理解,我将稍微转换一下您的代码:

For you to understand, I will transform your code just a tiny bit:

CollectionReference reference = Firestore.instance.collection('planets');
reference.snapshots().listen((querySnapshot) {
  querySnapshot.documentChanges.forEach((change) {
    // Do something with change
  });
});

您也不应该在事务中运行它.Flutter 方法是使用 StreamBuilder,直接来自 cloud_firestore Dart 发布页面:

You should also not run this in a transaction. The Flutter way of doing this is using a StreamBuilder, straight from the cloud_firestore Dart pub page:

StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance.collection('books').snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) return new Text('Loading...');
    return new ListView(
      children: snapshot.data.documents.map((DocumentSnapshot document) {
        return new ListTile(
          title: new Text(document['title']),
          subtitle: new Text(document['author']),
        );
      }).toList(),
    );
  },
);

如果你想了解更多,可以看看来源,有据可查,但不言自明.

If you want to know any more, you can take a look at the source, it is well documented, where it is not self-explanatory.

另请注意,我将 docChanges 更改为 documentChanges.您可以在 query_snapshot 文件.如果您使用的是 IntelliJ 或 Android Studio 等 IDE,点击其中的文件也很容易.

Also take note that I changed docChanges to documentChanges. You can see that in the query_snapshot file. If you are using an IDE like IntelliJ or Android Studio, it is also pretty easy to click through the files in it.

这篇关于如何使用 Flutter 侦听 Cloud Firestore 中的文档更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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