data_util.dart 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import 'dart:math';
  2. final storageUnits = ["bytes", "KB", "MB", "GB"];
  3. String convertBytesToReadableFormat(int bytes) {
  4. int storageUnitIndex = 0;
  5. while (bytes >= 1024 && storageUnitIndex < storageUnits.length - 1) {
  6. storageUnitIndex++;
  7. bytes = (bytes / 1024).round();
  8. }
  9. return bytes.toString() + " " + storageUnits[storageUnitIndex];
  10. }
  11. String formatBytes(int bytes, [int decimals = 2]) {
  12. if (bytes == 0) return '0 bytes';
  13. const k = 1024;
  14. final int dm = decimals < 0 ? 0 : decimals;
  15. final int i = (log(bytes) / log(k)).floor();
  16. return ((bytes / pow(k, i)).toStringAsFixed(dm)) + ' ' + storageUnits[i];
  17. }
  18. //shows 1st decimal only if less than 10GB & omits decimal if decimal is 0
  19. num roundBytesUsedToGBs(int usedBytes, int freeSpace) {
  20. const tenGBinBytes = 10737418240;
  21. num bytesInGB = convertBytesToGBs(usedBytes);
  22. if ((usedBytes >= tenGBinBytes && freeSpace >= tenGBinBytes) ||
  23. bytesInGB % 1 == 0) {
  24. bytesInGB = bytesInGB.truncate();
  25. }
  26. return bytesInGB;
  27. }
  28. //Eg: 0.3 GB, 11.0 GB, 532.3 GB
  29. num convertBytesToGBs(int bytes) {
  30. return num.parse((bytes / (pow(1024, 3))).toStringAsFixed(1));
  31. }
  32. int convertBytesToMBs(int bytes) {
  33. return (bytes / pow(1024, 2)).round();
  34. }