简体   繁体   中英

Flutter Firebase local change doesn't update listener stream

I'm relying on Firebase Firestore offline capabilities, so I'm not using await on my queries as stated on the Access Data Offline Firebase doc . I'm expecting that when I write something I'll get an immediate reflection on my read stream, however, I'm only getting an update when the server/remote has been updated. Basically:

  1. Update something in the DB. Note, I'm not using await
 _db.doc(parentDoc).collection(DocInnerCollection).doc(childDoc).update({
        "name": value,
      });
  1. I expect my listeners to be updated immediately. Note I've set the includeMetadataChanges to true as stated in the above doc.
_db.doc(parentDoc)
    .collection(DocInnerCollection)
    .orderBy('start_date', 'desc')
    .limitToLast(1)
    .snapshots(includeMetadataChanges: true)
    .map((snapshot) {
  print(snapshot.metadata.isFromCache)
});

However, I get no such update and instead I only get an update when the server has been updated.

You're requesting only one document with .limitToLast(1) , yet are not providing a sort order for your query. This essentially means that you'll get a random document from your collection, and the chances of that being the newly updated document are close to zero.

If you want the latest (not just last) document, you need some ordering criteria to determine what latest means. Typically you'd do this by:

  1. Adding a lastUpdated field to your documents, and setting that to firebase.firestore.FieldValue.serverTimestamp() .
  2. Ordering your query on that timestamp with orderBy('lastUpdated', 'desc') .
  3. And then limiting to the first result with limit(1) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM