listMailboxesAsTree method

Future<Tree<Mailbox?>> listMailboxesAsTree({
  1. bool createIntermediate = true,
  2. List<MailboxFlag> order = defaultMailboxOrder,
})

Lists all mailboxes/folders of the incoming mail server as a tree in the specified order.

Optionally set createIntermediate to false, in case not all intermediate folders should be created, if not already present on the server.

Implementation

Future<Tree<Mailbox?>> listMailboxesAsTree(
    {bool createIntermediate = true,
    List<MailboxFlag> order = defaultMailboxOrder}) async {
  final mailboxes = _mailboxes ?? await listMailboxes();
  List<Mailbox>? firstBoxes;
  firstBoxes = sortMailboxes(order, mailboxes, keepRemaining: false);
  final boxes = [...mailboxes];
  boxes.sort((b1, b2) => b1.path.compareTo(b2.path));
  final separator = _account.incoming?.pathSeparator ?? '/';
  final tree = Tree<Mailbox?>(null);
  tree.populateFromList(
      boxes,
      (child) => child!.getParent(boxes, separator,
          createIntermediate: createIntermediate));
  final parent = tree.root!;
  final children = parent.children;
  for (var i = firstBoxes.length; --i >= 0;) {
    final box = firstBoxes[i];
    var element = _extractTreeElementWithoutChildren(parent, box);
    if (element != null) {
      if (element.children?.isEmpty ?? true) {
        // this elemement has been removed:
        element.parent = parent;
      } else {
        element = TreeElement<Mailbox?>(box, parent);
      }
      children!.insert(0, element);
    }
  }

  return tree;
}