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?
>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()