buildTree method

List<CNode> buildTree(
  1. List<CNode> list,
  2. String? parentID
)

Implementation

List<CNode> buildTree(List<CNode> list, String? parentID) {
  final nodes = list.where((n) => n.parentID == parentID).toList();

  // Sort nodes based on childOrder
  nodes.sort((a, b) => a.childOrder.compareTo(b.childOrder));

  List<CNode> children = [];
  for (var node in nodes) {
    if (node.intrinsicState.canHave == ChildrenEnum.children) {
      final children0 = buildTree(list, node.id);
      children.add(node.copyWith(
        children: children0,
        parentID: parentID,
      ));
    } else if (node.intrinsicState.canHave == ChildrenEnum.child) {
      final children0 = buildTree(list, node.id);
      children.add(node.copyWithOutChild(
          child: children0.isNotEmpty
              ? list.any((element) => element.id == children0.first.id)
                  ? children0.first
                  : null
              : null,
          parentID: parentID));
    } else {
      children.add(node.copyWith(parentID: parentID));
    }
  }
  return children;
}