skip to Main Content

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


  1. 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:

    //If the current index is less than the maximum index (length - 1), then there is a later index to compare to.
    if (index < (food.length - 1)){
        if (DateTime(food[index].todaysDate.day) != DateTime(food[index + 1].todaysDate.day)){
        ....//Rest of code here
        }
    }
    
    

    This way, it won’t check if there isn’t a later date to compare to and you should avoid the RangeError.

    Login or Signup to reply.
  2. 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 the length - 1 in your condition:

    if (index < (food.length -1) && DateTime(food[index].todaysDate.day) != DateTime(food[index + 1].todaysDate.day)) ...[
                                    Divider(color: Colors.blue),
                                    Text("NewDay"),
                                    Divider(),
                                  ],
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search