getDirectorySize function

Future<int> getDirectorySize(
  1. String path, {
  2. bool recursive = false,
  3. bool cacheSize = false,
  4. bool verbose = false,
})

Implementation

Future<int> getDirectorySize(String path,
    {bool recursive = false,
    bool cacheSize = false,
    bool verbose = false}) async {
  try {
    int totalSize = 0;
    if (verbose) await prnt("\r${trunc("> Check dir size of $path")}");
    final entityList = await Directory(path)
        .list(recursive: false, followLinks: true)
        .toList();

    await Future.forEach(entityList, (entity) async {
      if (entity is File) {
        totalSize += await getFileSize(entity.path,
            cacheSize: cacheSize, verbose: verbose);
      } else if (entity is Directory) {
        totalSize += await getDirectorySize(entity.path,
            recursive: true, cacheSize: cacheSize, verbose: verbose);
      }
    });

    if (verbose)
      await prnt("${trunc("\r>> Size of dir $path")} is $totalSize bytes");

    if (cacheSize) {
      FileInformationCache FIC = FileInformationCache.obtain();
      FileInfo FI = FileInfo(path: path, size: totalSize, isFile: false);
      FIC.addFile(path, FI);
    }

    return totalSize;
  } catch (E) {
    return 0;
  }
}