Hello i am working with fire store database for making one to one chat between user. Here i want some pagination of messages. So i called snapshot listener inside initState So the problem is while i navigate to chat screen, initState called snapshot listener DocumentType.added automatically. so data becomes duplicate..
here is my code which i called inside initState
List<DocumentSnapshot> _products = [];
StreamController<List<DocumentSnapshot>> _streamController =
StreamController<List<DocumentSnapshot>>.broadcast();
@override
void initState() {
db
.collection('chat')
.document(docId)
.collection('messages')
.orderBy('timestamp', descending: true)
.snapshots().listen((data) => onChangeData(
data.documentChanges,
));
}
void onChangeData(
List<DocumentChange> documentChanges,
) {
documentChanges.forEach((productChange) {
if (productChange.type == DocumentChangeType.removed) {
_products.removeWhere((product) {
return productChange.document.documentID == product.documentID;
});
_streamController.add(_products);
}
if (productChange.type == DocumentChangeType.added) {
_products.insert(productChange.newIndex, productChange.document);
_streamController.add(_products);
}
if (productChange.type == DocumentChangeType.modified) {
int indexWhere = _products.indexWhere((product) {
return productChange.document.documentID == product.documentID;
});
if (indexWhere >= 0) {
_products[indexWhere] = productChange.document;
}
_streamController.add(_products);
}
});
}
onChangeData
method. Is this a list you have previously filtered between the data your had locally and the new data coming fromFirestore
? You mention that this is a 1 to 1 chat, but your variables are_products
are these the messages? – João SoaresClear
your list on the top and thenadd
– BloodLoss