buildTreeEntries<E> method

List<E> buildTreeEntries<E>({
  1. required List<T> roots,
  2. required bool isExpanded(
    1. T node
    ),
  3. required List<T> getChildren(
    1. T node
    ),
  4. required E createEntry(
    1. T node,
    2. int depth,
    3. bool isLast,
    4. List<bool> ancestorLines,
    ),
})

Builds visible entries from a tree structure.

roots - Root nodes of the tree. isExpanded - Check if a node is expanded. getChildren - Get children of a node. createEntry - Create a visible entry from node + metadata.

Implementation

List<E> buildTreeEntries<E>({
  required List<T> roots,
  required bool Function(T node) isExpanded,
  required List<T> Function(T node) getChildren,
  required E Function(
          T node, int depth, bool isLast, List<bool> ancestorLines)
      createEntry,
}) {
  final result = <E>[];

  void traverse(T node, int depth, bool isLast, List<bool> ancestorLines) {
    result.add(createEntry(node, depth, isLast, ancestorLines));

    if (isExpanded(node)) {
      final children = getChildren(node);
      for (var i = 0; i < children.length; i++) {
        final child = children[i];
        final childIsLast = i == children.length - 1;
        traverse(
          child,
          depth + 1,
          childIsLast,
          [...ancestorLines, !isLast],
        );
      }
    }
  }

  for (var i = 0; i < roots.length; i++) {
    traverse(roots[i], 0, i == roots.length - 1, const []);
  }

  return result;
}