Is there a way to get a default value from a Map in dart (like Java):
static Map DEFAULT_MAPPING = Map.unmodifiable({
"k1": "value"
});
DEFAULT_MAPPING['k1'] //get 'value'
DEFAULT_MAPPING.getOrElse('non-present-key', 'default-value') //something like Java has
The default value will be null Uninitialized variables have an initial value of null.
Dart Map is an object that stores data in the form of a key-value pair. Each value is associated with its key, and it is used to access its corresponding value. Both keys and values can be any type. In Dart Map, each key must be unique, but the same value can occur multiple times.
If your map does not contains null values, you can use if null operator:
var map = {
'a': 1,
'b': 2,
};
var cValue = map['c'] ?? 3;
Alternativelly you can define your own extension method:
extension DefaultMap<K,V> on Map<K,V> {
V getOrElse(K key, V defaultValue) {
if (this.containsKey(key)) {
return this[key];
} else {
return defaultValue;
}
}
}
var map = {
'a': 1,
'b': 2,
};
var cValue = map.getOrElse('c', 3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With