How to get key by value in a Dart map

A Dart Map allows you to get value by key. What about getting key by value?

Using the keys property and the firstWhere() method of the List class, we can get key by specifying value.

The Dart method firstWhere() iterates over the entries and returns the first one that satisfies the criteria or condition.

Syntax

map_name.keys.firstWhere(bool test(T element), {T orElse()})

map_name is the name of the map

Return type

The firstWhere() method returns the first element that satisfies the given criteria.

If no element satisfies the condition, the result of invoking the orElse function is returned.

If orElse isn’t specified, a StateError is thrown by default.

Code

The following code illustrates how to get key by value using the keys property and firstWhere() method.

void main() {
// Creating Map named map
Map map = {1: 'Pen', 2: 'Book', 3: 'Ruler', 4: 'Bag'};
// Using keys property and firstWhere() method
// to get key in a map
var key = map.keys.firstWhere((k) => map[k] == 'Bag', orElse: () => null);
print('The key for value "Bag" : ${key}');
}

Suppose the value "Bag" is not found in the map. The orElse result will be displayed.

The key for value "Bag": null