formatFileSize property

string get formatFileSize

Returns a formatted string representation of the file size.

The file size is represented in bytes and is formatted as follows:

  • If the size is less than 1024 bytes, it is returned as is with the suffix "bytes".
  • If the size is between 1024 bytes (inclusive) and 1024^2 bytes (exclusive), it is converted to kilobytes (KB) and returned with two decimal places.
  • If the size is between 1024^2 bytes (inclusive) and 1024^3 bytes (exclusive), it is converted to megabytes (MB) and returned with two decimal places.
  • If the size is between 1024^3 bytes (inclusive) and 1024^4 bytes (exclusive), it is converted to gigabytes (GB) and returned with two decimal places.
  • If the size is between 1024^4 bytes (inclusive) and 1024^5 bytes (exclusive), it is converted to terabytes (TB) and returned with two decimal places.
  • If the size is greater than or equal to 1024^5 bytes, it is converted to petabytes (PB) and returned with two decimal places.

Example:

int fileSize = 1500;
String formattedSize = fileSize.formatFileSize;
print(formattedSize); // Output: "1.46 KB"

Implementation

string get formatFileSize {
  if (this < 1024) {
    return "$this bytes";
  } else if (this < pow(1024, 2)) {
    return "${(this / 1024).toStringAsFixed(2)} KB";
  } else if (this < pow(1024, 3)) {
    return "${(this / pow(1024, 2)).toStringAsFixed(2)} MB";
  } else if (this < pow(1024, 4)) {
    return "${(this / pow(1024, 3)).toStringAsFixed(2)} GB";
  } else if (this < pow(1024, 5)) {
    return "${(this / pow(1024, 4)).toStringAsFixed(2)} TB";
  } else {
    return "${(this / pow(1024, 5)).toStringAsFixed(2)} PB";
  }
}