Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get key from Map<String,List<String>> knowing one of the List values

I have a map

Map<String, List> map1 = {a: [1,2,3,4], b: [5,6,7,8], c: [9,10,11]};

I know one of the values of one of the lists – 1..11.
How can I get the key of a map entity where this value belongs to – a, b, c?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this, where search is the value you’re trying to find in the array.

Note that firstWhere can give you an error if the value cannot be found anywhere.

void main() {
  final data = {
    'a': [1, 2, 3, 4],
    'b': [5, 6, 7, 8],
    'c': [9, 10, 11]
  };

  final search = 4;

  final selected = data.keys.firstWhere((key) {
    return data[key]!.contains(search);
  });

  print(selected); // a
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading