Home > Mobile >  Nested loop in Flutter nested map and list
Nested loop in Flutter nested map and list

Time:06-17

I have this simple nested List inside List of Maps, how to iterate this variable? This code below raise an error.

A nullable expression can't be used as an iterator in a for-in loop.

void main() {
  final changes = [
    {
      'version': '1',
      'date': '3 Nov 2021',
      'content': [
        'Changes 1',
        'Changes 2',
      ],
    },
    {
      'version': '2',
      'date': '5 Nov 2021',
      'content': [
        'Changes 3',
        'Changes 4',
        ],
    },
  ];
  
  for (var el in changes) {
    for (var subEl in el['content']) {
      print (subEl);
    }
  }
}

CodePudding user response:

You have to state the type of the object.

void main() {
  final List<Map<String, dynamic>> changes = [
    {
      'version': '1',
      'date': '3 Nov 2021',
      'content': [
        'Changes 1',
        'Changes 2',
      ],
    },
    {
      'version': '2',
      'date': '5 Nov 2021',
      'content': [
        'Changes 3',
        'Changes 4',
        ],
    },
  ];
  
  for (var el in changes) {
    for (var subEl in el['content']) {
      print (subEl);
    }
  }
}

Screenshot with result

CodePudding user response:

Because el is a map, it doesn't know if el['content'] is null or if it's even a list, you can cast it to List like this to make it work.

for (var el in changes) {
  for (var subEl in (el['content'] as List)) {
    print (subEl);
  }
}

This code will crash if it happens to not be a list, you could make it safer like this for example

for (var el in changes) {
  var list = el['content'];
  if (list is List) {
    for (var subEl in list) {
      print (subEl);
    }   
  }
}
  • Related