How to get data index from List Dart

Viewed 879

I have the list data like this

void main() {
  var animals = [
    {
      "0": ["cow", "chicken", "Fish"]
    },
    {
      "1": ["lamb", "Camel"]
    },
    {
      "2": ["Goat", "Cat"]
    }
  ];
  print(animals.length);
  for (var a in animals) {
for (final x in a.entries){
print (x.value)}
}

}

but I want to get data to become like this:

1. cow 
2. chicken
3. fish
1. lamb
2. camel
1. goat
2. cat

So, what can I do to get the output? Thank you I have tried to use join, but it is just for making a new line. not get the index.

Using x.value.join("\n")

3 Answers
void main() {
  var animals = [
    {
      "0": ["cow", "chicken", "Fish"]
    },
    {
      "1": ["lamb", "Camel"]
    },
    {
      "2": ["Goat", "Cat"]
    }
  ];
  for(var i in animals) {
    for(var j in i.entries) {
      for(var k = 0; k < j.value.length;k++) {
        print("${k+1}. ${j.value[k]}"); 
      }
    }
  }
}

Using List.asMap() would enumerate the list into indexes as keys to each associated value in the same order the list was.

The following code generates the desired output. Try running it on DartPad:

void main() {
  var animals = [
    {
      "0": ["cow", "chicken", "Fish"]
    },
    {
      "1": ["lamb", "Camel"]
    },
    {
      "2": ["Goat", "Cat"]
    }
  ];
  for (final a in animals) {
    for (final x in a.values) {
      for (final y in x.asMap().entries) {
        print('${y.key + 1}. ${y.value}');
      }
    }
  }
}

OUTPUT

1. cow
2. chicken
3. Fish
1. lamb
2. Camel
1. Goat
2. Cat
Related