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]..sort((b1, b2) => b1.path.compareTo(b2.path));
  final separator = (mailboxes.isNotEmpty)
      ? mailboxes.first.pathSeparator
      : _account.incoming.pathSeparator;
  final tree = Tree<Mailbox?>(null)
    ..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 element has been removed:
        element.parent = parent;
      } else {
        element = TreeElement<Mailbox?>(box, parent);
      }
      children?.insert(0, element);
    }
  }

  return tree;
}