Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access map keys through index? Dart

Tags:

dart

dartques = {'Color':[], 'Fruits':[], 'Hobbies':[]};

How to access the values using index in map? I need to access only key or value using index. Just like we do in list
=>list[1]

like image 589
Raghav Singh Avatar asked Mar 03 '20 17:03

Raghav Singh


2 Answers

You can convert it to two lists using keys and values methods:

var ques = {'Color':['a'], 'Fruits':['b'], 'Hobbies':['c']};
List keys = ques.keys.toList();
List values = ques.values.toList();
print (keys);
print (values);

The output:

[Color, Fruits, Hobbies]
[[a], [b], [c]]

So you can access it normally by using keys[0], for example.

like image 135
Naslausky Avatar answered Oct 05 '22 23:10

Naslausky


For accessing the values by index, there are two approaches:

  1. Get Key by index and value using the key:

     final key = dartques.keys.elementAt(index);
     final value = dartques[key];
    
  2. Get value by index:

     final value = dartques.values.elementAt(index);
    

You may choose the approach based on how and what data are stored on the map.

For example if your map consists of data in which there are duplicate values, I would recommend using the first approach as it allows you to get key at the index first and then the value so you can know if the value is the wanted one or not.

But if you do not care about duplication and only want to find a value based on Index then you should use the second approach, as it gives you the value directly.

Note: As per this Answer By Genchi Genbutsu, you can also use Extension methods for your convenience.

Important: Since the default implementation for Map in dart is LinkedHashmap you are in great luck. Otherwise Generic Map is known for not maintaining order in many programming languages.

If this was asked for any other language for which the default was HashMap, it might have been impossible to answer.

like image 24
Harshvardhan Joshi Avatar answered Oct 06 '22 01:10

Harshvardhan Joshi