May 28, 2023

How to get the size of a directory including its files

This is a example walk a directory recursively (sync version). Async version can be done with dir.list() and its listen() method.

Map<String, int> dirStatSync(String dirPath) {
  int fileNum = 0;
  int totalSize = 0;
  var dir = Directory(dirPath);
  try {
    if (dir.existsSync()) {
      dir.listSync(recursive: true, followLinks: false)
        .forEach((FileSystemEntity entity) {
          if (entity is File) {
            fileNum++;
            totalSize += entity.lengthSync();
          }
        });
    }
  } catch (e) {
    print(e.toString());
  }

  return {'fileNum': fileNum, 'size': totalSize};
}

Leave a Reply