fileSize static method

String fileSize(
  1. int bytes, [
  2. int decimals = 0
])

Converts a file size in bytes to a human-readable format with appropriate units.

bytes: The size of the file in bytes. decimals: The number of decimal places to include in the result. Default is 0. Returns a string representing the file size with appropriate units (bytes, kilobytes, megabytes, etc.).

Implementation

static String fileSize(int bytes, [int decimals = 0]) {
  // If the file size is 0 or negative, return "0 B"
  if (bytes <= 0) return "0 B";

  // List of suffixes for different units (bytes, kilobytes, megabytes, etc.)
  const suffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

  // Calculate the index of the appropriate unit based on the logarithm of the file size
  var i = (log(bytes) / log(1024)).floor();

  // Calculate the size in the appropriate unit and convert it to a string with the specified number of decimals
  return '${(bytes / pow(1024, i)).toStringAsFixed(decimals)} ${suffixes[i]}';
}