parse static method
Parses a dynamic value v
into an integer.
Tries to convert the dynamic value v
into an integer. It supports parsing
from int, BigInt, List<int>
, and String types. If v
is a String and
represents a hexadecimal number (prefixed with '0x' or not), it is parsed
accordingly.
allowHex: convert hexadecimal to integer
Parameters:
v
: The dynamic value to be parsed into an integer.
Returns:
- An integer representation of the parsed value.
Implementation
static int parse(dynamic v, {bool allowHex = true}) {
try {
if (v is int) return v;
if (v is BigInt) {
if (!v.isValidInt) {
throw ArgumentException("value is to large for integer.",
details: {"value": "$v"});
}
return v.toInt();
}
if (v is String) {
int? parse = int.tryParse(v);
if (parse == null && allowHex && StringUtils.ixHexaDecimalNumber(v)) {
parse = int.parse(StringUtils.strip0x(v), radix: 16);
}
return parse!;
}
} catch (_) {}
throw ArgumentException("invalid input for parse int",
details: {"value": "$v"});
}