Flutter Error: RangeError (index): Invalid value: Not in range 0..2, inclusive: 3
You should pass the itemCount
parameter to the ListView.builder
to allow it to know the item count
Widget getList() {
List<String> list = getListItems();
ListView myList = new ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return new ListTile(
title: new Text(list[index]),
);
});
return myList;
}
This error occurs when you run out of values when iterating over an array. In the case of the ListView
component missing the itemCount prop, the component attempts to continue to iterate but is unaware when to complete so it eventually continues on out of range (the length of the array).
You could also see this error after running a poorly set up for loop
. For example:
var arr = [1, 2, 3];
for (var i=0; i < 4; i++) {
print(arr[i]);
}
This dart code would result in a range error as well. The array has 3 items yet we attempt to iterate 4 times.