I have a list inside a ListView.builder
.
Inside the list are dates. I want to compare the date on the current index with the next date (index + 1). If it is different, I want to add a headline:
if (DateTime(food[index].todaysDate.day) != DateTime(food[index + 1].todaysDate.day)) ...[
Divider(color: Colors.blue),
Text("NewDay"),
Divider(),
],
But when I do it like that I get a "RangeError (index): Invalid value: Not in inclusive range
". It is running out of range because of the index + 1
. What can I do to fix it?
2
Answers
You need to make sure that the value of
index
is always one less than the maximum valid value. The easiest way to do this is to wrap your expression in another if statement:This way, it won’t check if there isn’t a later date to compare to and you should avoid the RangeError.
Be careful about the last index of your list,
imagine that your list has 9 indexes and you do not have the tenth one.
if you want to compare be sure that the
index
is less that thelength - 1
in your condition: