calcTemporaryDirectoryCacheSize function

Future<String> calcTemporaryDirectoryCacheSize()

Implementation

Future<String> calcTemporaryDirectoryCacheSize() async {
  Future<double> getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return double.parse(length.toString());
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        double total = 0;
        for (final FileSystemEntity child in children)
          total += await getTotalSizeOfFilesInDir(child);
        return total;
      }
      return 0;
    } catch (err) {
      logError(err);
      return 0;
    }
  }

  convertSize(double value) {
    List<String> unitArr = []
      ..add('B')
      ..add('K')
      ..add('M')
      ..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  try {
    Directory tempDir = await getTemporaryDirectory();
    double value = await getTotalSizeOfFilesInDir(tempDir);
    return convertSize(value);
  } catch (err) {
    logError(err);
  }
  return "";
}