How can I fetch data from Firestore only once each even if I modify some fields?

Viewed 565

I'm developing a flutter app and I have a problem that I can't solve. On one of my views, I display all my users from Firestore. I first Query to Firestore, and I every time save the last user to re-execute the query with startAfterDocument(lastUser).

 fetch10first() async {
 Stream<QuerySnapshot> stream = dbInstance.collection('users').orderBy('prenom', descending: true).limit(10).snapshots();
 stream.listen((snapshot) {
  snapshot.documents.forEach((u) {
    User user = User.fromDocument(u);
    setState(() {
      users.add(user);
      _lastUser = u;
    });
  });
});
}

Every user is stored in a List. To display those users, I'm using a ListView.builder with a scroll controller that checks if I've reached the bottom of my page and fetches 10 new users. The problem I have is that I'm listening to snapshots. Then if I modify one of my users ( from the app or from Firestore ), it will get another snapshot and I'm going to have the user displayed twice. How can I solve this?

1 Answers

To fetch data only once, you need to use Future with getDocuments():

fetch10first() async {
 Future<QuerySnapshot> futureCol = dbInstance.collection('users').orderBy('prenom', descending: true).limit(10).getDocuments();
 futureCol.then((snapshot) {
  snapshot.documents.forEach((u) {
    User user = User.fromDocument(u);
    setState(() {
      users.add(user);
      _lastUser = u;
    });
  });
});
}
Related