Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating over children of a DataSnapshot throws exception

When I try to iterate over the children in a DataSnapshot it throws a RangeError. This is the code that I have:

  Map<String, Object> mapOfMaps(DataSnapshot snapshot) {
    Map<String, Object> map = <String, Object>{};

    for (var child in snapshot.children) {
      if (child.children.isNotEmpty) {
        map[child.key!] = mapOfMaps(child);
      } else {
        map[child.key!] = child.value!;
      }
    }

    return map;
  }

There are 7 children but the exception says: RangeError (index): Invalid value: Not in inclusive range 0..6: -1. Why is it trying to start iterating at -1?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue is likely related to the fact that snapshot.children property is returning Iterable object which may not have a defined length.

To solve it try to check snapshot.children.isNotEmpty before iterating.
Or convert it directly to the list: snapshot.children.toList()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading