28
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]

Ramin eghbalian
  • 2,348
  • 1
  • 16
  • 36
Raghav Singh
  • 281
  • 1
  • 3
  • 3
  • Does this answer your question? [Flutter/Dart: How to access a single entry in a map/object](https://stackoverflow.com/questions/53824755/flutter-dart-how-to-access-a-single-entry-in-a-map-object) – Mattia Mar 05 '20 at 18:28

3 Answers3

22

you can get it like this

var element = dartques.values.elementAt(0);

also for Dart 2.7+ you can write extension function

extension GetByKeyIndex on Map {
  elementAt(int index) => this.values.elementAt(index);
}

var element = dartques.elementAt(1);
19

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.

Harshvardhan Joshi
  • 2,855
  • 2
  • 18
  • 31
  • 1
    Great answer, thank you. Indeed the key is that dart's `Map` defaults to a [LinkedHashmap](https://api.dart.dev/stable/2.10.5/dart-collection/LinkedHashMap-class.html) which keeps the order. – lenz Mar 01 '21 at 04:10
15

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.

Naslausky
  • 3,443
  • 1
  • 14
  • 24