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]
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.
For accessing the values by index, there are two approaches:
Get Key by index and value using the key:
final key = dartques.keys.elementAt(index);
final value = dartques[key];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With