简体   繁体   中英

Flutter/Firestore - Streambuilder and Firestore with realtime listener

I'm trying to set up a Firestore stream inside a stream builder like how they showed in their doc but when I update a doc or delete one it doesn't get reflected on the screen. The logs gets updated but not the actual screen.

Code:

// Chats API file
Stream<List<Message>> messagesStream({String chatID, String orderBy, bool descending, List<dynamic> startAfter, int limit}) {
  return this
      .collection
      .document(chatID)
      .collection(Config.messages)
      .orderBy(orderBy, descending: descending)
      .startAfter(startAfter)
      .limit(limit)
      .snapshots()
      .map((event) => event.documents.map((documentSnapshot) => Message().model(id: documentSnapshot.documentID, map: documentSnapshot.data)).toList().reversed.toList());
}


// Chat file
Widget _streamBuilderWidget;

@override
void initState() {
  super.initState();

  this._streamBuilder();
  if (Platform.isIOS) {
    this._scrollController.addListener(() {
      if (this._scrollController.position.pixels <= -135.0) {
        this._checkForOldMessages();
      }
    });
  }
}

@override
Widget build(BuildContext context) {
    …
    Expanded(child: this._streamBuilderWidget),
    …
}

Widget _streamBuilder() {
  return this._streamBuilderWidget = StreamBuilder<List<Message>>(
      initialData: this._messages,
      stream: APIs().chats.messagesStream(chatID: widget.chat.chatID, orderBy: 'createdAt', descending: true, startAfter: this._startAfter, limit: this._messagesLimit),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            {
              return PAIndicator();
            }
          default:
            {
              if (snapshot.data.length < this._messagesLimit) {
                this._hasMoreMessages = false;
              } else {
                this._hasMoreMessages = true;
              }

              snapshot.data.forEach((m) {
                print(m.message); // Prints 10 values even when 1 file is changed
              });

              this._messages.insertAll(0, snapshot.data);

              return Platform.isIOS
                  ? MessagesList(mKey: this._listKey, scrollController: this._scrollController, messages: this._messages, aUser: widget.aUser)
                  : RefreshIndicator(
                      child: MessagesList(mKey: this._listKey, scrollController: this._scrollController, messages: this._messages, aUser: widget.aUser),
                      onRefresh: () async {
                        await Future.delayed(Duration(seconds: 1));

                        this._checkForOldMessages();

                        return null;
                      });
            }
        }
      });
}

Also, when I send a message it doesn't get added to the list, I have to go back and enter the chatroom again to see the latest message.

How can I have it so that when I open the chat room I can see the new messages coming in while just showing the most recent messages to reduce costs, I don't want to show all 10000 messages. Just the most recent ones and the ones that are being added to it while users are in the chatroom.

Note: I have it like this because for somereason whenever I'm typing it keeps reloading and when I scroll the array just multiplies itself and what not. This is the only way I have add older messages to the array as I scroll that I know of.

The new messages do not show until I re-enter the chatroom.

With regards to how to only show the most recent messages, you should be implementing paginated queries and lazy load the older messages after a certain scroll point.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM