Sorting messages by date in Flutter / Dart

I’m working on a chat app using Flutter and Firebase for data storage. Right now, I’m having trouble sorting and displaying messages correctly by date.

Here’s the code I’m using to sort and display the messages:

Widget _buildMessageList() {
  String senderId = _authService.getCurrentUser()!.uid;
  Stream<fc.QuerySnapshot> currentStream;
  
  if (widget.isGroupChat) {
    currentStream = _chatService.getMessagesFromGroup(widget.receiverID);
  } else {
    currentStream = _chatService.getMessages(widget.receiverID, senderId);
  }
  
  return StreamBuilder<fc.QuerySnapshot>(
    stream: currentStream,
    builder: (context, snapshot) {
      if (snapshot.hasError) {
        return Center(child: Text("Error: ${snapshot.error}"));
      }

      if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(child: CircularProgressIndicator());
      }

      if (!snapshot.hasData || snapshot.data!.docs.isEmpty) {
        return Center(child: Text("No messages"));
      }

      // Extrahiere die Nachrichten und sortiere nach Datum
      List<fc.DocumentSnapshot> messages = snapshot.data!.docs;
      messages.sort((a, b) {
        DateTime timeA = (a['timestamp'] as fc.Timestamp).toDate();
        DateTime timeB = (b['timestamp'] as fc.Timestamp).toDate();
        return timeA.compareTo(timeB);
      });

      // Gruppierung und Anzeige nach Datum
      List<MessageElement> messageElements = [];
      DateTime? currentDate;

      for (var message in messages) {
        DateTime messageDate = (message['timestamp'] as fc.Timestamp).toDate();

        // Prüfe, ob eine neue Gruppe (Datum) begonnen werden muss
        if (currentDate == null || !isSameDay(currentDate!, messageDate)) {
          messageElements.add(MessageElement(
            timeBubble: true,
            dataBox: message,
            displayTimeMessage: _formatDate(messageDate),
            time: message['timestamp'],
          ));
          currentDate = messageDate;
        }

        // Füge die Nachricht hinzu
        messageElements.add(MessageElement(
          timeBubble: false,
          dataBox: message,
          displayTimeMessage: _formatDate(messageDate),
          time: message['timestamp'],
        ));
      }

      return GroupedListView<dynamic, String>(
        elements: messageElements,
        groupBy: (element) => element.displayTimeMessage,
        groupSeparatorBuilder: (String groupByValue) => TimeBubble(day: groupByValue),
        itemBuilder: (context, element) => _buildMessageItem(element.dataBox, element.timeBubble, ""),
        order: GroupedListOrder.DESC,
        reverse: true,
        controller: _scrollController,
      );
    },
  );
}

// Überprüft, ob zwei DateTime Objekte den gleichen Tag haben
bool isSameDay(DateTime dateA, DateTime dateB) {
  return dateA.year == dateB.year && dateA.month == dateB.month && dateA.day == dateB.day;
}

// Formatierung des Datums für die Anzeige
String _formatDate(DateTime date) {
  return "${date.year}-${date.month}-${date.day}";
}

The issue is that sometimes messages with later dates (e.g., “2024-7-12”) are appearing before messages with earlier dates (e.g., “2024-7-3”). I’ve used the compareTo() method to compare DateTime objects, but the sorting doesn’t seem to be working correctly.

Could someone please check my code and help me fix the sorting problem? I’m not sure what I’m doing wrong and would appreciate any assistance.

Thanks!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật