toFileSize method

String toFileSize({
  1. int decimals = 2,
})

Converts the number (bytes) to a human-readable file size string.

Example:

print(1024.toFileSize()); // Output: 1.00 KB

Implementation

String toFileSize({int decimals = 2}) {
  if (this <= 0) return "0 B";
  const suffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  var i = (log(this) / log(1024)).floor();
  if (i == 0) return "${toInt()} B";
  return '${(this / pow(1024, i)).toStringAsFixed(decimals)} ${suffixes[i]}';
}