safeParseInt function

int safeParseInt(
  1. dynamic value, {
  2. int fallback = 0,
})

Safely parses a dynamic value to an int.

This function attempts to convert the provided value to an int. If the value is null, an invalid number, or cannot be parsed, the fallback value is returned instead.

  • Parameters:

    • value: A dynamic value that is expected to be convertible to an int.
    • fallback: An int value to return if parsing fails or if value is null. Defaults to 0 if not provided.
  • Returns: An int representation of the value if parsing succeeds, or the fallback value if it fails.

  • Example:

safeParseInt('123');       // returns 123
safeParseInt(null);        // returns 0 (fallback)
safeParseInt('abc', fallback: 10);  // returns 10 (fallback)
safeParseInt(15);          // returns 15 (automatic conversion from int)

Implementation

int safeParseInt(dynamic value, {int fallback = 0}) {
  return int.tryParse((value ?? fallback).toString()) ?? fallback;
}