toFileSize method
Formats this number (bytes) as a human-readable file size string.
1048576.toFileSize() // '1.0 MB'
1536.toFileSize() // '1.5 KB'
512.toFileSize() // '512 B'
Implementation
String toFileSize({int decimals = 1}) {
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
var value = toDouble();
var unitIndex = 0;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex++;
}
final formatted = unitIndex == 0
? value.toStringAsFixed(0)
: value.toStringAsFixed(decimals);
return '$formatted ${units[unitIndex]}';
}