toFileSize method

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

Converts bytes to a human-readable string (e.g., "1.5 MB").

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 = (math.log(this) / math.log(1024)).floor();
  if (i >= suffixes.length) {
    i = suffixes.length - 1;
  }
  return '${(this / math.pow(1024, i)).toStringAsFixed(decimals)} ${suffixes[i]}';
}