How to get Map keys by values in Dart?
Solution 1:
var usdKey = curr.keys.firstWhere(
(k) => curr[k] == 'USD', orElse: () => null);
Solution 2:
If you will be doing this more than a few times on the same data, you should create an inverse map so that you can perform simple key lookup instead of repeated linear searches. Here's an example of reversing a map (there may be easier ways to do this):
main() {
var orig = {"01": "USD", "17": "GBP", "33": "EUR"};
var reversed = Map.fromEntries(orig.entries.map((e) => MapEntry(e.value, e.key)));
for (var kv in reversed.entries) {
print(kv);
}
}
Edit: yes, reversing a map can simply be:
var reversed = orig.map((k, v) => MapEntry(v, k));
Tip of the hat to Joe Conway on gitter. Thanks.
Solution 3:
There is another one method (similar to Günter Zöchbauer answer):
void main() {
Map currencies = {
"01": "USD",
"17": "GBP",
"33": "EUR"
};
MapEntry entry = currencies.entries.firstWhere((element) => element.value=='GBP', orElse: () => null);
if(entry != null){
print('key = ${entry.key}');
print('value = ${entry.value}');
}
}
In this code, you get MapEntry, which contains key and value, instead only key in a separate variable. It can be useful in some code.
Solution 4:
Map map = {1: 'one', 2: 'two', 3: 'three'};
var key = map.keys.firstWhere((k) => map[k] == 'two', orElse: () => null);
print(key);