0
votes

I'm trying to return a FutureBuilder from a SearchDelegate but result shown are not correct.

query seems to be correct and from network I can see all http calls done correctly, so the problem is related to the list data update itself.

In buildSuggestions (of SearchDelegate) a StatefulWidget called 'ResultList' is returned. This widget has for state:

  1. previousQuery - last search term before rerendering
  2. list - list of data returned from a Future
  3. from - first element to show
  4. pageSize - number of elements returned

I need those variables in order to implement infinite scroll so in ResultList build method first of all I check if widget.query has changed from last rendering

if (previousQuery != widget.query) {
  setState(() {
    from = 0;
    list.clear();
    previousQuery = widget.query;
  });
}

I'm using a ScrollController, so in initState of ResultList when user reach the bottom of the screen i just update "from":

setState(() {
    from += pageSize;
});

In FutureBuilder builder method, if snapshot has new data, I append it to list. I should update list in setState but I can't do this inside a builder.

builder: (context, snapshot) {
      List<int> ids = [];
      List<int> newids = [];
      if (snapshot.hasData) {
        ids = list.map((item) => item.id as int).toSet().toList();
        newids = (snapshot.data.results as List)
            .map((item) => item.id as int)
            .toSet()
            .toList()
            .where((id) => !ids.contains(id))
            .toList();
        if (newids.length != 0) {
           setState(() {//can't do this here
               list = [
                   ...list,
                   ...(snapshot.data.results as List)
                       .where((element) => newids.contains(element.id as int))
               ];
           });
        }    
      }

Any hint? Thanks in advance.

1
Isn't the FutureBuilder setting the state by default - so no need/possibility to set the state within? Just a hint since you are reputation wise comparable to me: Have a look into BLoC. It cost me 2 days to get in, but working with business logic and states is now a charmw461
did you mean bloclibrary.dev?assistbss
yes, the extensions bloc and flutter_blocw461
thanks I'll give it a tryassistbss

1 Answers

0
votes

when we Use Future Builder Inside of StateFull Widget we Should know On Every SetState Future Builder call Future Function. and rebuild it self, so your problem is going to solve if you Remove Future Builder ,

so please change your code to some thing like below...

  @override
  Widget build(BuildContext context) {
    return newids.Empty && ids.Empty ? CircularProgressIndicator() : MyWidget();
  }

and Call Your Future in Init State (and When You Want get new Items(next page))