test firma
test firma

Reputation: 351

check if the map has a specific string in it's keys, then give me it's value, that belong this key, Dart

may i ask how to check if the map of String,String has in it's keys a specific String then i want to get the value that belong this specific key that contains the target String. for example this Map

Map<String, String> ListFinalAllInfos = {'stackoverflow': 'one', 'google': 'two'};

and i want to check if this map has this String in it's keys

stackoverflow

if stackoverflow exists as a key inside the map then i want to get the value which is

one

without converting the map to a list, if this possible. thanks in advance

Upvotes: 24

Views: 38077

Answers (2)

harpreet seera
harpreet seera

Reputation: 1818

You can use the containsKey(Object? key) method of map to know whether it is having a matching key. This method returns true if this map contains the given [key]. So in context to your question, to check whether map has this key just use:

final hasKey = listFinalAllInfos.containsKey("stackoverflow");

Now you know whether the map has the key or not. Based on that, to get value of respective key just use:

final valueOfKey = listFinalAllInfos["stackoverflow"];

This will return you the value associated to the key in the map.

Upvotes: 11

cyberail
cyberail

Reputation: 1284

Map<String, String> ListFinalAllInfos = {'stackoverflow': 'one', 'google': 'two'};
String key = ListFinalAllInfos.containsKey("stackoverflow"); // search for the key. for example stackoverflow
String value = ListFinalAllInfos[key]; // get the value for the key, value will be 'one'
if(ListFinalAllInfos.containsKey(value)){ //check if there is a key which is the value you grabbed
  return true;
}

Upvotes: 29

Related Questions