getTreeString method

String getTreeString({
  1. String indent = '',
  2. bool isLast = true,
  3. bool showFiles = true,
  4. int? maxDepth,
  5. int currentDepth = 0,
})

Returns a string representation of the tree structure

Same as printTree but returns the result as a string instead of printing

Example:

final treeString = folder.getTreeString();
print(treeString);

Implementation

String getTreeString({
  String indent = '',
  bool isLast = true,
  bool showFiles = true,
  int? maxDepth,
  int currentDepth = 0,
}) {
  final buffer = StringBuffer();

  // Check depth limit
  if (maxDepth != null && currentDepth >= maxDepth) {
    return buffer.toString();
  }

  // Add current folder
  final folderName = p.basename(path);
  final prefix = indent + (isLast ? '└── ' : '├── ');
  buffer.writeln('$prefix$folderName/');

  // Prepare next level indent
  final nextIndent = indent + (isLast ? '    ' : '│   ');

  // Sort children: folders first, then files
  final folders = children.whereType<AssetLookupFolder>().toList();
  final files = showFiles
      ? children.whereType<AssetLookupFile>().toList()
      : <AssetLookupFile>[];

  // Sort folders and files alphabetically
  folders.sort((a, b) => p.basename(a.path).compareTo(p.basename(b.path)));
  files.sort((a, b) => a.basename.compareTo(b.basename));

  final allItems = [...folders, ...files];

  // Add children
  for (int i = 0; i < allItems.length; i++) {
    final child = allItems[i];
    final isLastChild = i == allItems.length - 1;

    if (child is AssetLookupFolder) {
      buffer.write(
        child.getTreeString(
          indent: nextIndent,
          isLast: isLastChild,
          showFiles: showFiles,
          maxDepth: maxDepth,
          currentDepth: currentDepth + 1,
        ),
      );
    } else if (child is AssetLookupFile) {
      final filePrefix = nextIndent + (isLastChild ? '└── ' : '├── ');
      buffer.writeln('$filePrefix${child.basename}');
    }
  }

  return buffer.toString();
}