tryToInt function

int? tryToInt(
  1. dynamic object, {
  2. Object? mapKey,
  3. int? listIndex,
})

Attempts to convert an object to an int, or returns null if the object is null or conversion fails. mirroring the same static method in the ConvertObject, providing alternative easy less code usage options.

  • 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 = tryToInt(object1); // 10

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

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

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

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

Implementation

int? tryToInt(
  dynamic object, {
  Object? mapKey,
  int? listIndex,
}) =>
    ConvertObject.tryToInt(object, mapKey: mapKey, listIndex: listIndex);