safeParseInt function
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:
-
Returns: An int representation of the
value
if parsing succeeds, or thefallback
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;
}