tryToInt static method

int? tryToInt(
  1. dynamic object, {
  2. dynamic mapKey,
  3. String? format,
  4. String? locale,
  5. int? listIndex,
})

Attempts to convert an object to an int, or returns null if the object is null or conversion fails.

  • Converts numeric types and strings that represent valid integers to int.
  • If the conversion to int fails (e.g., non-integer string), logs an error and returns null.

object The object to be converted to an int. mapKey (Optional) Specifies the key to extract values from a Map object. listIndex (Optional) Specifies the index to extract elements from a List object.

Returns an int if conversion is successful, otherwise null.

Example usage:

final object1 = 10;
final int1 = ConvertObject.tryToInt(object1); // 10

final object2 = '5';
final int2 = ConvertObject.tryToInt(object2); // 5

final object3 = true;
final int3 = ConvertObject.tryToInt(object3); // 1

final object4 = 'abc';
final int4 = ConvertObject.tryToInt(object4); // null

final object5 = null;
final int5 = ConvertObject.tryToInt(object5); // null

Implementation

static int? tryToInt(
  dynamic object, {
  dynamic mapKey,
  String? format,
  String? locale,
  int? listIndex,
}) {
  if (object is int?) return object;

  if (mapKey != null && object is Map<dynamic, dynamic>) {
    return tryToInt(object[mapKey]);
  }
  if (listIndex != null && object is List<dynamic>) {
    return tryToInt(object.of(listIndex));
  }
  try {
    if (format.isNotBlank) {
      return '$object'.tryToIntFormatted(format, locale);
    }
    return '$object'.tryToInt;
  } catch (e, s) {
    log(
      'tryToInt() Unsupported object type: exception message -> $e',
      stackTrace: s,
      error: e,
    );
    return null;
  }
}