1

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);
    }
  }
}

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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);
    }   
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.