Reginaldo Rigo
Reginaldo Rigo

Reputation: 297

How to reset ListView.Builder index

child: FutureBuilder(
     future: getTasks(),
     builder: (context, snapshot) {
       if (task != null && task.tasks.length > 0) {
         return ListView.builder(
           shrinkWrap: true,
           itemCount: task.tasks.length,
           itemBuilder: (context, index) {
             return task.tasks[index].start_date == selecteddate
                 ? TarefaCard(
                     width: MediaQuery.of(context).size.width * 0.8,
                     title: task.tasks[index].description,
                     howlong: task.tasks[index].howlong_str,
                     icon: Icon(icons[0]),
                     indice: index,
                     onPress: _setActiveTask )
                 : Container();
           },
         );
       } else {
         return Center(
           child: CircularProgressIndicator(),
         );
       }
 }),

This code when execute for the first time calls the API and loads my class named task with all the tasks from 15 days. The last 7 days, today and the next 7 days. This JSON file is sorted by date so I can make a list of all dates users have in that period of time. So the first ones have the older dates.

With those dates I create a ButtonMenu and the users can select which tasks they want to see by selecting a date.

When it's called the next time, the method getTasks() does not call the API anymore, it just uses the JSON that was loaded before.

Unfortunately this code does not work all the time because the value of index variable changes all the time and for my benefit ListView.builder trying to be efficient does not reset the index to 0 all the time.

Then this part of the code

return task.tasks[index].start_date == selecteddate

fails and does not show the task related to the selecteddate as it should.

Because the user browsed the file to the last date the index is high, now if he tries to see the first date the index is too high and [index].start_date is not equal to selecteddate

How could I reset this variable or my approach is totally wrong and should be implemented totally different?

Upvotes: 1

Views: 688

Answers (1)

Sami Haddad
Sami Haddad

Reputation: 1436

Instead of checking the start_date inside the itemBuilder, compute a filteredTasks and use it in your ListView:

var filteredTasks = tasks.where((task) => task.start_date == selecteddate)

Upvotes: 2

Related Questions