John
John

Reputation: 2811

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.

Upvotes: 5

Views: 2327

Answers (1)

Omatt
Omatt

Reputation: 10519

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.

Upvotes: 1

Related Questions