Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Firestore stream does not update when using order by clause

I am returning a stream from firestore using the below:

Stream<CompletedExerciseList> getExerciseStream(String uid, {int limit}) {

Stream<QuerySnapshot> snapshots;

try {
  CollectionReference exerciseCollection = Firestore.instance.collection('users').document(uid).collection('completed_exercise');

  if (limit != null) {
    snapshots = exerciseCollection.orderBy('startTime', descending: false).orderBy('name', descending: true).limit(limit).snapshots();
  } else {
    snapshots = exerciseCollection.orderBy('startTime', descending: false).orderBy('name', descending: true).snapshots();
  }
} catch (e) {
  print(e);
}

return snapshots.map((list) => CompletedExerciseList(list.documents.map((doc) => ExerciseModel.fromMap(doc.data)).toList()));
}

The above method returns a stream on widget build but when the documents in the collection are updated the stream is not updated. However if I remove the orderBy clause the stream updates correctly when documents are added/deleted from the collection. So the below code works, however I need to be able to order and limit the results of the snapshot.

Stream<CompletedExerciseList> getExerciseStream(String uid, {int limit}) {

Stream<QuerySnapshot> snapshots;

try {
  CollectionReference exerciseCollection = Firestore.instance.collection('users').document(uid).collection('completed_exercise');

  if (limit != null) {
    snapshots = exerciseCollection.limit(limit).snapshots();
    } else {
    snapshots = exerciseCollection.snapshots();
    }
} catch (e) {
  print(e);
}

return snapshots.map((list) => CompletedExerciseList(list.documents.map((doc) => ExerciseModel.fromMap(doc.data)).toList()));
}

For both scenarios no error is printed to my console. I'm using Android Studio with the Flutter SDK.

like image 622
John Avatar asked Nov 16 '22 19:11

John


1 Answers

You should be able to check for snapshot errors on your StreamBuilder. As for sorting your Firestore data, you need to set up an index.

like image 138
Omatt Avatar answered May 31 '23 18:05

Omatt