updateMessageBuffer method

void updateMessageBuffer(
  1. List<AbstractChatMessage> messages
)

Implementation

void updateMessageBuffer(List<AbstractChatMessage> messages) {
  WidgetsBinding.instance.addPostFrameCallback((_) {
    String lastAddedId =
        messageBuffer.value.isNotEmpty ? messageBuffer.value.last.id : "";
    Map<String, AbstractChatMessage> messageMap = {};
    for (var message in messageBuffer.value) {
      messageMap[message.id] = message;
    }

    for (var message in messages) {
      messageMap[message.id] = message;
    }

    messageBuffer.add(messageMap.values
        .sorted((a, b) => a.timestamp.compareTo(b.timestamp)));

    String lia =
        messageBuffer.value.isNotEmpty ? messageBuffer.value.last.id : "";

    if (lastAddedId != lia) {
      bool self = messageBuffer.value.last.senderId == widget.sender;
      bool mostlyDown = scrollController.position.maxScrollExtent -
              scrollController.position.pixels <
          250;

      if (mostlyDown || self) {
        Future.delayed(16.ms, () async {
          int g = 5;
          while (g-- > 0 &&
              scrollController.position.pixels <
                  scrollController.position.maxScrollExtent) {
            scrollController
                .jumpTo(scrollController.position.maxScrollExtent);
            await Future.delayed(Duration(milliseconds: 16));
          }
        });
      }
    }
  });
}