90

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

1
  • 19
    add itemCount parameter to ListView.builder() constructor Commented Dec 29, 2018 at 7:53

12 Answers 12

169

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;
}
Sign up to request clarification or add additional context in comments.

10 Comments

What if my list doesn't have a fixed length (e.g. In infinite scrolling)?
@RichardMcFriendOluwamuyiwa Listview.builder is for a list with a specified length, you can use listview if you don`t know the length
it doesn't help in case with AnimatedList, unfortunately
I am using SliverList, where i dont find any option for specifying itemCount :(
@ElhamKeshavarz your comment is wrong and misleading. This is the official description of the listview.builder: This constructor is appropriate for list views with a large (or infinite) number of children because the builder is called only for those children that are actually visible. Providing a non-null itemCount improves the ability of the ListView to estimate the maximum scroll extent.
|
18

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.

Comments

5

if you use substring and if did not make condition properly then you will get an error

3 Comments

its range issue, not related to substring
final showd = note.description.length > 60 ? note.description.substring(0, 50) : note.description; here you will get range error also
I was using substring(0, 3) on a value that has only 1 character..placing a check of string.length solved the problem...mentioning the substring attribute led me to the culprit...thnx
3

In my case, my itemCount:list.lenght parameter was fine but somewhere in my listTile, I used wrong parameter for list.indexWhere() function .When I fix function, error was gone.

1 Comment

Yes, you get the error in the outer list, but it may also have to do with a range error in another list called in the tile. Thank you!
2

If you are using StreamBuilder then you must use this line of code:

  StreamBuilder(
                  stream: FirebaseFirestore.instance.collection("Tooth")
                  .orderBy("date", descending: false).snapshots() ,
                
                  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
                 
                    if(snapshot.hasData)
                    {
                      return ListView.builder(
                        itemCount: snapshot.data.docs.length,
                          padding: const EdgeInsets.only( top: 20.0),
                        itemBuilder: (BuildContext context, int index) {
                           DocumentSnapshot ds = snapshot.data.docs[index];
 },
                      );
                    }
                   
                  },
                ),

Comments

1

The Listview.Builder contains itemcount attribute. You could try this:

Listview.Builder(
    itemCount : list.length,
    itemBuilde:(context, index)=>
);

1 Comment

Than you for providing an answer. Unfortunately, your answer is just a duplicate of the accepted answer. In the future, please try to provide context with your answers, or explanations as to why the answer you are providing correctly solves the problem.
1

You miss the item count.

itemCount: item.length///item is your list name

hope answer the Question

Comments

0

This mainly occurs when you are using wrong index value to fetch data from list. in my case, I was doing the same mistake.

Comments

0

This type Error Call indexoutofboundsexception in java but in dart case you get error like this
RangeError (index): Invalid value: Not in inclusive range 0..12: 13..........................#0
but you have write int lastElement = myList[myList.length]; instant of this **
int lastElement = myList[myList.length - 1];**
for example

  List<int> myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
int lastElement = myList[myList.length - 1]; // Accessing the 12th element

Comments

-1

In my case also this error was due to substring on null value i just removed or used ?? and it solved "RangeError (index): Invalid value: Not in range 0..2, inclusive: 3" error.

1 Comment

I was asking issue in my code 4 years ago, anyway, issue was with the length that I missed back then
-1

For me I was using SliverGrid but it's the same concept as the accepted answer.

SliverGrid(
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 3,
                            crossAxisSpacing: 4,
                            mainAxisSpacing: 4,
                          ),
                          delegate: SliverChildBuilderDelegate(
                              childCount: snapshot.data!.length,
                              (context, index) {
[more code]
}

Adding the childCount on the Sliver Delegate solved this issue for me.

Comments

-2
Widget getListView(){
  var itemList = getListElement();
   var list = ListView.builder(
     itemCount: itemList.length,
       itemBuilder:(context, index){
         return ListTile(
           title: Text(itemList[index]),   
         );
         }
   );
   return list;
}

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.