magicInt method

int magicInt({
  1. int defaultValue = 0,
})

Converts the value to an int.

  • defaultValue: The value to return if the conversion fails or the value is null.

Implementation

int magicInt({int defaultValue = 0}) {
  if (isNull) return defaultValue;

  if (this is double) return this as int;

  if (this is int) return this as int;

  if (this is String) {
    return int.tryParse(this as String) ?? defaultValue;
  }

  if (this is bool) return (this as bool) ? 1 : 0;

  if (this is List) {
    double sum = 0;
    for (var element in this as List) {
      if (element is num) {
        sum += element;
      }
    }
    return sum.toInt();
  }

  if (this is Map) {
    double sum = 0;
    for (var value in (this as Map).values) {
      if (value is num) {
        sum += value;
      }
    }
    return sum.toInt();
  }

  if (this is DateTime) {
    return (this as DateTime).millisecondsSinceEpoch;
  }

  if (this is Set) {
    double sum = 0;
    for (var element in this as Set) {
      if (element is num) {
        sum += element;
      }
    }
    return sum.toInt();
  }

  if (this is Queue) {
    double sum = 0;
    for (var element in this as Queue) {
      if (element is num) {
        sum += element.toDouble();
      }
    }
    return sum.toInt();
  }

  log(
    'Unsupported Data Type: ${this?.runtimeType.toString()}',
    name: 'NINJA UI EXTENSION',
  );
  return defaultValue;
}