I have a map with dynamic values, one of which can be an int
, string
or null
(i.e. non-existing key).
I want to store this value in an int
variable. The parsing I came up with ended up being quite cumbersome:
Map<String, dynamic> map = {'maxposts': null}; // or 23 or '42'
// Try to parse an int value or fall back to 0
int maxposts = (map['maxposts'] is int)
? map['maxposts']
: int.tryParse(map['maxposts'] ?? '0') ?? 0;
Is there a nicer way of doing such a "try-fallback" parsing?
You can abstract the operation into a function like
int intOrStringValue(dynamic o) {
if (o is String) o = int.tryParse(o);
return o ?? 0;
}
or
int intOrStringValue(dynamic o) =>
(o is String ? int.tryParse(o) : o) ?? 0;
It gets more readable when you don't repeat the map['maxposts']
expression throughout the logic.