Home > OS >  How to reload a FutureBuilder in Flutter?
How to reload a FutureBuilder in Flutter?

Time:10-11

I have a FutureBuilder here :

FutureBuilder<List<Task>>(
                          future:
                            getTasks(),
                          builder: (BuildContext context, AsyncSnapshot<List<Task>> snapshot){
                            if(snapshot.hasError){
                              return const Text('Erreur');
                            }
                            if(snapshot.hasData){
                              return ListView(
                                shrinkWrap: true,
                                physics: NeverScrollableScrollPhysics(),
                                children: taskList.map((e) => TaskContainer(
                                  task: e
                                )).toList(),
                              );
                            }
                            return const Center(child: CircularProgressIndicator());
                          }
                        )

Which return a list of tasks as colored block container in a calendar as shown below :

enter image description here

The problem is whenever I navigate to another month in the calendar, the FutureBuilder is fetching the again fetching the data from the webservice, which duplicate the tasks every time I change months :

enter image description here

Here is the code of my functions to navigate between months :

    _toPreviousMonth(){
    setState(() {
      datess.clear();
      dayss.clear();
      startMonth = new DateTime(startMonth.year, startMonth.month - 1, 1);
    });
  }

  _toNextMonth(){
    setState(() {
      datess.clear();
      dayss.clear();
      startMonth = new DateTime(startMonth.year, startMonth.month   1, 1);
    });
  }

Actually I don't mind the FutureBuilder fetching the data when I change month, because the final goal would be to display tasks from the selected day.

But what I would like is to have a way to suppress the containers build from the previous fetch as I navigate between months,

Thanks for helping :)

CodePudding user response:

Your code is not showing how you are using snapshot in your FututrBuilder??

I suspect you are adding the tasks directly to a list everytime you re-build using setState( ).

Solution: reset your tasks list at the beginning of the buid( ) method

@override Widget build(BuildContext context) {
yourTaskList = [] //if an array or adjust if other type
  • Related