0
votes

I created a flutter application with two tabs. On the first tab I have a ListView that displays information from a StreamBuilder. This StreamBuilder gets data over http.

The problem is : when I switch to the second tab and then back to first tab, the ListView reloads.

Before I used a StatefulWidget with AutomaticKeepAliveClientMixin but now i'm using a StatelessWidget so I can't use it anymore. I think my build method need to pure but I don't know how to do this. I saw that within a StatefulWidget there is the initState() method but it is the same problem, I can't use it.

class ListImmeubleTab extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    bloc.fetchAllImmeubles();
    return Scaffold(
        body: StreamBuilder(
            stream: bloc.allImmeubles,
            builder: (context, AsyncSnapshot<List<ImmeubleModel>> snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (BuildContext context, int index) {
                      String color;
                      switch(index % 3){
                        case 0:
                          color = "green";
                          break;
                        case 1:
                          color = "blue";
                          break;
                        case 2:
                          color = "red";
                          break;
                      }
                      return ListTile(
                        leading: CircleAvatar(
                          child: Image.asset("assets/houses/house_$color.png"),
                        ),
                        title: Text(snapshot.data[index].numero.toString() + " " + snapshot.data[index].rue),
                        subtitle: Text(snapshot.data[index].zip.toString() + " " + snapshot.data[index].ville),
                      );
                    }
                );
              } else if (snapshot.hasError) {
                return Text(snapshot.error.toString());
              }
              return Center(child: CircularProgressIndicator());
            }
        )
    );
  }
}
1
Just convert your StatelessWidget to a StatefulWidget - Rémi Rousselet
Does this follow the bloc architecture ? And is it good using AutomaticKeepAliveClientMixin or is it a little bit tricky ? - louisld

1 Answers

0
votes

Try adding a postFrame callback


class Test extends StatelessWidget {

  _callBack(_){

  }

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback(_callBack);
    return Container();
  }
}