0

I would like to get access to all indexes in my map. Since the number of variables in the list changes.

I tried something like this but it did not work

final fruitList = ['apple', 'orange', 'mango', 'variable', ''variable2'];
final fruitMap = myList.asMap(); // {0: 'apple', 1: 'orange', 2: 'mango'}

print(fruitMap[0-5])

I could imagine that you have to make a loop but I had no success in making a loop for this map. The loop should continue until every index in the map is worked through. So that you will only print[i] and output as if print[0-5] was there

MarcelK
  • 72
  • 7
  • 3
    Does this answer your question? [Enumerate or map through a list with index and value in Dart](https://stackoverflow.com/questions/54898767/enumerate-or-map-through-a-list-with-index-and-value-in-dart) – Zakria Khan Oct 24 '20 at 16:48

1 Answers1

3

This has been answered here already, but the short answer is:

void main() {
  final list = ['Apple', 'Orange', 'Mango', 'Strawberry'];
  list.asMap().forEach((index, item) => print("$index: $item"));
}
// Output:
// 0: Apple
// 1: Orange
// 2: Mango
// 3: Strawberry

Using .asMap() returns the index and item, and then you can .forEach() through each index-item pair.

Lineous
  • 1,642
  • 8
  • 8