如何使用Flutter监听Cloud Firestore中的文档更改? [英] How to listen for document changes in Cloud Firestore using Flutter?
问题描述
我想有一个侦听器方法,如果发生更改,它会检查文档集合的更改。
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
的文档,您可以看到来自 Query
的流
可以通过 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屋!