dirsTree method

Future<List<Directory>> dirsTree({
  1. List<String>? excludedPaths = const ["/storage/emulated/0/Android"],
  2. bool followLinks = false,
  3. bool excludeHidden = false,
  4. FlutterFileUtilsSorting? sortedBy,
})

Return list tree of directories. You may exclude some directories from the list.

  • excludedPaths will excluded paths and their subpaths from the final list
  • sortedBy: FlutterFileUtilsSorting
  • bool reversed: in case parameter sortedBy is used

Implementation

Future<List<Directory>> dirsTree(
    {List<String>? excludedPaths = const ["/storage/emulated/0/Android"],
    bool followLinks: false,
    bool excludeHidden: false,
    FlutterFileUtilsSorting? sortedBy}) async {
  List<Directory> dirs = [];

  try {
    var contents = root.listSync(recursive: true, followLinks: followLinks);
    if (excludedPaths != null) {
      for (var fileOrDir in contents) {
        if (fileOrDir is Directory) {
          for (var excludedPath in excludedPaths) {
            if (!p.isWithin(excludedPath, p.normalize(fileOrDir.path))) {
              if (!excludeHidden) {
                dirs.add(Directory(p.normalize(fileOrDir.absolute.path)));
              } else {
                if (!fileOrDir.absolute.path.contains(RegExp(r"\.[\w]+"))) {
                  dirs.add(Directory(p.normalize(fileOrDir.absolute.path)));
                }
              }
            }
          }
        }
      }
    } else {
      for (var fileOrDir in contents) {
        if (fileOrDir is Directory) {
          if (!excludeHidden) {
            dirs.add(Directory(p.normalize(fileOrDir.absolute.path)));
          } else {
            // The Regex below is used to check if the directory contains
            // ".file" in pathe
            if (!fileOrDir.absolute.path.contains(RegExp(r"\.[\w]+"))) {
              dirs.add(Directory(p.normalize(fileOrDir.absolute.path)));
            }
          }
        }
      }
    }
  } catch (error) {
    throw FileManagerError(permissionMessage + error.toString());
  }
  if (dirs != null) {
    return sortBy(dirs, sortedBy) as FutureOr<List<Directory>>;
  }

  return dirs;
}