Home > Enterprise >  Screen not updated after calling FutureBuilder again
Screen not updated after calling FutureBuilder again

Time:12-16

I have a screen that loads shopping cart items in a ListView.builder:

Expanded(
                    child: RefreshIndicator(
                        onRefresh: refresh,
                        child: Container(
                          child: FutureBuilder(
                            future: loadData(),
                            builder: (context, snapshot) {
                              if (snapshot.hasData) {

      List<dynamic>? filteredList = snapshot.data as List;
...

The data are loaded using the function loadData()

 Future<List<LineaCesta>> loadData() async {
    await fetchLineasCesta(idCesta);
    return fetchLineasCesta(idCesta);
  }

Then, inside the item card, there are some buttons to add or remove product quantity.

Here you have the case for adding a new one:

onPressed:  () async {
//añadir uno maas
final prefs = await SharedPreferences.getInstance(); 
idCesta = prefs.getString("cesta_id")!;
checkExistenciaCestaPoner( idCesta!,lineaCesta.producto,lineaCesta.precio,context); 
print(  "refrescando despues de añadir item"); 
   });
  });
}

Then there are called other functions that at the end are calling the function loadData() again.

The issue is that all made changes are not updated after calling loadData.

I need to leave the screen and load it again to get all data updated.

EDIT:

Future<List<LineaCesta>> fetchLineasCesta(String cesta) async {


  String url = Constantes().URLProyecto Constantes().APICarpeta "get_lineas_cesta.php?cesta=" cesta;
  final response = await http.get(Uri.parse(url));

  return lineaCestaFromJson(response.body);

}

CodePudding user response:

When you like to refresh the FutureBuilder, reassing the future variable. For this I will prefer creating a separate variable for FutureBuilder's future.

 late Future<List<LineaCesta>> loadDateFuture = loadData();

And use

FutureBuilder<List<LineaCesta>>(
  future: loadDateFuture,

Now to update, reassign the loadDateFuture

loadDateFuture = loadData(); // like this 

You can check Randal L. Schwartz's video

  • Related