Flutter Error: RangeError (index): Invalid value: Not in range 0..2, inclusive: 3

Issue

I am using a long list in Flutter. All the items are rendering fine but I also receive the following error:

RangeError (index): Invalid value: Not in range 0..2, inclusive: 3

The following is my code:

@override
Widget build(BuildContext context) {
return Container(
  child: getList(),
 );
}

The following is my getList() method:

Widget getList (){
List<String> list = getListItems();
ListView myList = new ListView.builder(itemBuilder: (context, index){
  return new ListTile(
    title: new Text(list[index]),
  );
});
return myList;
}

And the following is my getListItem() method:

List<String> getListItems(){
return ["Faizan", "Usman", "Naouman"];
}

the following is the screenshot of error:

enter image description here

Solution

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

Answered By – muttonlamb

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published