Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value in dart Map

Tags:

dart

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
like image 387
C.P.O Avatar asked Jan 14 '20 14:01

C.P.O


People also ask

What is the default value of variable in Dart?

The default value will be null Uninitialized variables have an initial value of null.

What is map () in Dart?

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.


Video Answer


1 Answers

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);
like image 138
Alexandre Ardhuin Avatar answered Oct 05 '22 04:10

Alexandre Ardhuin