[英]flutter local notification on firestore change
In my firestore I have a list of documents which represent locations on a map.在我的 firestore 中,我有一个代表地图上位置的文档列表。
I would like to show a local notification not only when a new document is created in the database, but also when the location is within a certain distance from my current location.我想不仅在数据库中创建新文档时显示本地通知,而且当该位置与我的当前位置相距一定距离时也显示本地通知。
At the moment I have a streambuilder which loads the position into my local map, and a streamlistener to give a notification on a new document:目前,我有一个 streambuilder 将位置加载到我的本地地图中,还有一个 streamlistener 来通知新文档:
CollectionReference loc =
FirebaseFirestore.instance.collection('locations');
late Stream<QuerySnapshot> _locStream;
late StreamSubscription<QuerySnapshot> streamSub;
@override
void initState() {
super.initState();
_locStream = loc.snapshots();
streamSub = _locStream.listen((data) {
final snackBar = SnackBar(
content:
Text('New location added!'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
});
}
the problem is that the stream is returning ALL the documents, not only the new one, so I have no idea how to "isolate" the new one and, more important, how to get its value in order to compare it with my current location.问题是流正在返回所有文档,而不仅仅是新文档,所以我不知道如何“隔离”新文档,更重要的是,如何获取其值以便将其与我当前的位置进行比较.
Is that possible to achieve so?有可能实现吗?
A Firestore QuerySnapshot
always contains all information that fits within the query. Firestore QuerySnapshot
始终包含适合查询的所有信息。 But when the QuerySnapshot
is an update on an existing listener/stream, it also contains metadata about what changes compared to the previous QuerySnapshot
on the listener/stream.但是,当QuerySnapshot
是对现有侦听器/流的更新时,它还包含有关与侦听器/流上的先前QuerySnapshot
相比发生哪些变化的元数据。
To get access to this metadata, use the QuerySnapshot
's docChanges
property , rather than docs
, and check the DocumentChangeType
of the type
property of each change to find only the documents that were added.要访问此元数据,请使用QuerySnapshot
的docChanges
属性,而不是docs
,并检查每个更改的type
属性的DocumentChangeType
以仅查找添加的文档。 In the initial snapshot that will be all of the documents, since all of them are new to the snapshot at that point.在初始快照中,将是所有文档,因为此时所有文档都是新的快照。
See the Firebase documentation on viewing changes between snapshots请参阅有关查看快照之间的更改的 Firebase 文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.