arrayToTree function

List arrayToTree(
  1. List list,
  2. String idKey, {
  3. String parentKey = 'parentId',
})

Implementation

List arrayToTree(List list, String idKey, {String parentKey = 'parentId'}) {
  final map = {};
  // 创建节点映射
  for (final item in list) {
    map[item[idKey]] = {...item, "children": null};
  }
  // 构建树结构
  final List result = [];
  for (final item in list) {
    if (item[parentKey] == 0 || item[parentKey] == null) {
      result.add(map[item[idKey]]);
    } else {
      map[item[parentKey]]?['children'] ??= [];
      map[item[parentKey]]?['children']?.add(map[item[idKey]]);
    }
  }
  return result;
}