2

Ive got a simple chat feature in my app, only text. Right now Im using a StreamProvider utilizing the Provider package. Like this:

return MultiProvider(
      providers: [
        FutureProvider.value(
            value: DatabaseProvider().getDMProfile(pairing.dmId)),
        FutureProvider.value(
            value: DatabaseProvider().getPlayerProfile(pairing.playerId)),
        StreamProvider.value(value: ChatProvider().streamMessages(chatName)),
      ],
      child: ChatScreen(
        hidden: isPlayer ? pairing.playerHidden : pairing.dmHidden,
        isPlayer: isPlayer,
        chatName: chatName,
      ),
    );

Heres the code for the stream:

Stream<List<Message>> streamMessages(String chatId) {
    var ref = db
        .collection(CHAT_COLLECTION)
        .document(chatId)
        .collection(MESSAGES_COLLECTION)
        .orderBy('timestamp', descending: true);
    return ref.snapshots().map((list) =>
        list.documents.map((doc) => Message.fromMap(doc.data)).toList());
  }

This all works fine as I create a ListView to display the chats. What Im wondering is if pulling all the messages like that is the right way to do it for efficiency. And if not, how can I add in pagination so as the user scrolls up it loads additional past messages.

DRing
  • 6,825
  • 6
  • 29
  • 45

1 Answers1

0

Yes pulling all the messages like that can cost u a lot in the long run. You would need to look into pagination.

With query cursors in Cloud Firestore, you can split data returned by a query into batches according to the parameters you define in your query.

https://firebase.google.com/docs/firestore/query-data/order-limit-data

 var ref = db
    .collection(CHAT_COLLECTION)
    .document(chatId)
    .collection(MESSAGES_COLLECTION)
    .orderBy('timestamp', descending: true).startAfter(<Date>).limit(<Number of documents you want to fetch>);

One u understand this logic, you need to detect when to fetch additional data, u can do this by detecting user's scroll.

More about it here: How to check if scroll position is at top or bottom in ListView?

Once you understand both, you can come up with the pagination solution.

Mozes Ong
  • 1,204
  • 1
  • 11
  • 20