fetchMoreMessage method
Fetches more messages for a chat.
pageSize
: The number of messages to fetch.
chatId
: The ID of the chat.
Implementation
@override
Future<void> fetchMoreMessage(
int pageSize,
String chatId,
) async {
if (lastChat != chatId) {
_cumulativeMessages = [];
lastChat = chatId;
lastMessage = null;
}
// get the x amount of last messages from the oldest message that is in
// cumulative messages and add that to the list
var messages = <ChatMessageModel>[];
QuerySnapshot<FirebaseMessageDocument>? messagesQuerySnapshot;
var query = _db
.collection(_options.chatsCollectionName)
.doc(chatId)
.collection(_options.messagesCollectionName)
.orderBy('timestamp', descending: true)
.limit(pageSize);
if (lastMessage == null) {
messagesQuerySnapshot = await query
.withConverter<FirebaseMessageDocument>(
fromFirestore: (snapshot, _) =>
FirebaseMessageDocument.fromJson(snapshot.data()!, snapshot.id),
toFirestore: (user, _) => user.toJson(),
)
.get();
if (messagesQuerySnapshot.docs.isNotEmpty) {
lastMessage = messagesQuerySnapshot.docs.last;
}
} else {
messagesQuerySnapshot = await query
.startAfterDocument(lastMessage!)
.withConverter<FirebaseMessageDocument>(
fromFirestore: (snapshot, _) =>
FirebaseMessageDocument.fromJson(snapshot.data()!, snapshot.id),
toFirestore: (user, _) => user.toJson(),
)
.get();
if (messagesQuerySnapshot.docs.isNotEmpty) {
lastMessage = messagesQuerySnapshot.docs.last;
}
}
var messageDocuments = messagesQuerySnapshot.docs
.map((QueryDocumentSnapshot<FirebaseMessageDocument> doc) => doc.data())
.toList();
for (var message in messageDocuments) {
var sender = await _userService.getUser(message.sender);
if (sender != null) {
var timestamp = DateTime.fromMillisecondsSinceEpoch(
message.timestamp.millisecondsSinceEpoch,
);
messages.add(
message.imageUrl != null
? ChatImageMessageModel(
sender: sender,
imageUrl: message.imageUrl!,
timestamp: timestamp,
)
: ChatTextMessageModel(
sender: sender,
text: message.text!,
timestamp: timestamp,
),
);
}
}
_cumulativeMessages = [
...messages,
..._cumulativeMessages,
];
_cumulativeMessages.sort((a, b) => a.timestamp.compareTo(b.timestamp));
notifyListeners();
}