如何使用Flutter监听Cloud Firestore中的文档更改?
问题内容:
我希望有一个侦听器方法,如果发生更改,该方法将检查对文档集合的更改。
就像是:
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
。
有任何想法吗?
问题答案:
通过阅读cloud_firestore
文档,您可以看到可以从获取Stream
来自的。Query``snapshots()
为了让您理解,我将稍微转换一下代码:
CollectionReference reference = Firestore.instance.collection('planets');
reference.snapshots().listen((querySnapshot) {
querySnapshot.documentChanges.forEach((change) {
// Do something with change
});
});
您也不应在事务中运行它。该 颤振的方式 这样做的使用StreamBuilder
,直接从cloud_firestore
飞镖
酒吧页面
:
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(),
);
},
);
如果您想了解更多信息,可以查看源文件,该文件已被很好地记录下来,而不是不言自明的。
另请注意,我已更改docChanges
为documentChanges
。您可以在query_snapshot
文件中看到它。如果您使用的是IntelliJ或Android
Studio之类的IDE,也可以非常轻松地单击其中的文件。