humanReadableSize function

String humanReadableSize(
  1. int sizeInBytes
)

Converts a file size in bytes to a human-readable format (e.g., KB, MB, GB).

// 30: '30B', 5300: '5.2K', 2621440: '2.5M', 12884901888: '12.0G', 1099511627776: '1.0T', 1234567890123456: '1.1P',
print(humanReadableSize(30));   //  30B
print(humanReadableSize(5300)); // 5.2K
print(humanReadableSize(2621440)); // 2.5M

Implementation

String humanReadableSize(int sizeInBytes) {
  if (sizeInBytes < sizeKB) {
    return '${sizeInBytes}B';
  } else if (sizeInBytes < sizeMB) {
    return '${(sizeInBytes / sizeKB).toStringAsFixed(1)}K';
  } else if (sizeInBytes < sizeGB) {
    return '${(sizeInBytes / sizeMB).toStringAsFixed(1)}M';
  } else if (sizeInBytes < sizeTB) {
    return '${(sizeInBytes / sizeGB).toStringAsFixed(1)}G';
  } else if (sizeInBytes < sizePB) {
    return '${(sizeInBytes / sizeTB).toStringAsFixed(1)}T';
  } else {
    return '${(sizeInBytes / sizePB).toStringAsFixed(1)}P'; // or more
  }
}