getIntOrDefault method
Returns the integer value associated with the given key
,
or defaultValue
if the key does not exist or cannot be converted to int
.
Example:
final map = {'count': '10', 'views': 20};
print(map.getIntOrDefault('count', 0)); // Output: 10
print(map.getIntOrDefault('views', 0)); // Output: 20
print(map.getIntOrDefault('likes', 5)); // Output: 5
Implementation
int? getIntOrDefault(K key, int? defaultValue) {
if (!containsKey(key)) return defaultValue;
final value = this[key];
if (value is int) return value;
if (value is String) return int.tryParse(value) ?? defaultValue;
if (value is num) return value.toInt();
return defaultValue;
}