addAll method Null safety

void addAll(
  1. List<MimeMessage> unthreadedMessages
)

Distributes the given unthreadedMessages to the threads managed by this result.

Implementation

void addAll(List<MimeMessage> unthreadedMessages) {
  // the new messages could
  // a) complement existing threads, but only when threadPreference is ThreadPreference.all, or
  // b) create complete new threads
  final isUid = threadData.isUid;
  if (threadPreference == ThreadPreference.latest) {
    for (final node in threadData.children.reversed) {
      final id = node.latestId;
      final message = isUid
          ? unthreadedMessages.firstWhereOrNull((msg) => msg.uid == id)
          : unthreadedMessages
              .firstWhereOrNull((msg) => msg.sequenceId == id);
      if (message != null) {
        final thread = MimeThread(node.toMessageSequence(), [message]);
        threads.insert(0, thread);
      }
    }
    threads.sort((t1, t2) => isUid
        ? t1.latest.uid!.compareTo(t2.latest.uid!)
        : t1.latest.sequenceId!.compareTo(t2.latest.sequenceId!));
  } else {
    // check if there are messages for already existing threads:
    for (final thread in threads) {
      if (thread.hasMoreMessages) {
        final ids = thread.missingMessageSequence.toList().reversed;
        for (final id in ids) {
          final message = isUid
              ? unthreadedMessages.firstWhereOrNull((msg) => msg.uid == id)
              : unthreadedMessages
                  .firstWhereOrNull((msg) => msg.sequenceId == id);
          if (message != null) {
            unthreadedMessages.remove(message);
            thread.messages.insert(0, message);
          }
        }
      }
    }
    // now check if there are more threads:
    if (unthreadedMessages.isNotEmpty) {
      for (final node in threadData.children.reversed) {
        final threadSequence = node.toMessageSequence();
        final threadedMessages = <MimeMessage>[];
        final ids = threadSequence.toList();
        for (final id in ids) {
          final message = isUid
              ? unthreadedMessages.firstWhereOrNull((msg) => msg.uid == id)
              : unthreadedMessages
                  .firstWhereOrNull((msg) => msg.sequenceId == id);
          if (message != null) {
            threadedMessages.add(message);
          }
        }
        if (threadedMessages.isNotEmpty) {
          final thread = MimeThread(threadSequence, threadedMessages);
          threads.add(thread);
        }
      }
      threads.sort((t1, t2) => isUid
          ? t1.latest.uid!.compareTo(t2.latest.uid!)
          : t1.latest.sequenceId!.compareTo(t2.latest.sequenceId!));
    }
  }
}