flattenHierarchy function

List<(String, int)> flattenHierarchy(
  1. List<HierarchyUtils> nodes
)

Flattens tree: nodes has (id, parentId). Returns list of (id, level). Root level = 0.

The order is depth-first pre-order. Roots, and siblings, follow the order in which their ids first appear in nodes.

Ids are matched by exact string comparison: case and whitespace are significant, so 'a', 'A' and 'a ' are three different ids. A node is a root when its parentId is null, '', or names an id absent from nodes (a whitespace-only parentId is not '', so it is matched like any other id).

Exact duplicates (same id and same parent, root or child) are collapsed into one node. The walk is iterative, so deep chains do not overflow the stack.

Throws ArgumentError, naming the offending ids, when:

  • one id is listed with different parents (null and '' are the same "no parent" value);
  • any node cannot be reached from a root: a parent cycle, a self-parent, or a descendant of either.

Use validateHierarchy to get the same problems as data instead.

Example:

flattenHierarchy(<HierarchyUtils>[
  const HierarchyUtils('a', 'root'),
  const HierarchyUtils('root'),
]); // [('root', 0), ('a', 1)]

Audited: 2026-06-12 11:26 EDT

Implementation

List<(String, int)> flattenHierarchy(List<HierarchyUtils> nodes) {
  _throwIfInvalid(nodes);
  // Valid input has one parent per id, so a repeated row cannot change a value,
  // and the keys keep first-seen order (a repeated root is walked only once).
  final Map<String, String?> parents = HierarchyParent.firstListed(nodes);
  // An unknown parent id also makes a root, so an orphan subtree is not lost.
  final List<String> roots = parents.keys
      .where((String id) => !parents.containsKey(parents[id]))
      .toList();
  return _preOrder(roots, _childrenByParent(parents));
}