Search code examples
listdictionarydartindexingmap-function

How to get the index of each entry when call the map function on a map object in Dart / Flutter?


How to get the index of each entry in a Map<K, V> in Dart?

Specifically, can the index of each entry be printed out, if a map function is run on the object as shown in the below example?

e.g. how could I print out: MapEntry(Spring: 1) is index 0 MapEntry(Chair: 9) is index 1 MapEntry(Autumn: 3) is index 2 etc.

Map<String, int> exampleMap = {"Spring" : 1, "Chair" : 9, "Autumn" : 3};

void main() {  
  exampleMap.entries.map((e) { return print(e);}).toList(); ///print each index here
      }

-Note: I can get the index with a List object (e.g. by using exampleList.indexOf(e)) but unsure how to do this when working with a Map object.


Solution

  • You can use forEach and a variable to track the current index:

    Map<String, int> exampleMap = {"Spring": 1, "Chair": 9, "Autumn": 3};
    
    void main() {
      int i = 0;
      exampleMap.forEach((key, value) {
        print(i.toString());
        print(key);
        print(value);
        i++;
      });
    }