formatSize function

String formatSize(
  1. dynamic b
)

Format a byte count into a human-readable string (e.g., "1.5 MB").

Implementation

String formatSize(dynamic b) {
  int bytes = (b is int) ? b : int.tryParse(b.toString()) ?? 0;
  if (bytes <= 0) return '0 B';
  const s = ['B', 'KB', 'MB', 'GB', 'TB'];
  var i = 0;
  double v = bytes.toDouble();
  while (v >= 1024 && i < s.length - 1) {
    v /= 1024;
    i++;
  }
  return '${v.toStringAsFixed(1)} ${s[i]}';
}