I'm trying to implement Firebase streams and paging with my GetX. With my implementation the following problem arises. The initial batch of retrieved posts is successfully transmitted and updated in real time. However, the second batch of posts are not updated in real time. It appears that the stream is not linked to the second batch of posts. Here is the code:
ScrollController scrollController = ScrollController();
CollectionReference get _posts => FirebaseFirestore.instance.collection(FirebaseConstants.postsCollection);
RxList<PostModel> viewPost = RxList<PostModel>([]);
@override
void onInit() {
super.onInit();
viewPost.bindStream(getPosts());
}
Stream<List<PostModel>> getPosts() {
Stream<QuerySnapshot> snapshotStream;
void handleScroll() {
if (scrollController.position.maxScrollExtent ==
scrollController.position.pixels) {
var lastPost = viewPost.isNotEmpty ? viewPost.last : null;
_posts
.orderBy('createdAt', descending: true)
.startAfter([lastPost!.createdAt])
.limit(2)
.snapshots()
.listen((event) {
List<PostModel> newPosts = [];
for (var doc in event.docs) {
newPosts
.add(PostModel.fromMap(doc.data() as Map<String, dynamic>));
}
viewPost.addAll(newPosts);
});
}
}
scrollController.addListener(handleScroll);
snapshotStream =
_posts.orderBy('createdAt', descending: true).limit(7).snapshots();
return snapshotStream.map((event) {
List<PostModel> posts = [];
for (var doc in event.docs) {
posts.add(PostModel.fromMap(doc.data() as Map<String, dynamic>));
}
return posts;
});
}
I've tried several different implementations and always encounter the same problem. Posts are retrieved and displayed in the correct order. However, real-time updates work only for the initial batch of posts and not for the rest.