toBytes static method

num? toBytes(
  1. Object value, [
  2. String? unit
])

Converts a file size to bytes. Inverse of fileSize.

Pass either a parseable string ('1.5 KB') or a number with unit (Number.toBytes(1.5, 'KB')). Returns null on parse failure.

Implementation

static num? toBytes(Object value, [String? unit]) {
  if (value is num) {
    final mult = _byteUnits[(unit ?? 'B').toUpperCase()];
    if (mult == null) return null;
    return value * mult;
  }
  if (value is String) {
    final m = RegExp(
      r'^\s*(-?\d+(?:\.\d+)?)\s*([a-zA-Z]+)\s*$',
    ).firstMatch(value);
    if (m == null) return null;
    final num n = double.parse(m.group(1)!);
    final mult = _byteUnits[m.group(2)!.toUpperCase()];
    if (mult == null) return null;
    return n * mult;
  }
  return null;
}