how to setState inside streambuilder

2.7k views Asked by At

I have a streamBuilder inside a stateful widget that gets data asynchronously from the server. Additionally, I have a list that collects those data.

StreamBuilder(   
  stream: myStream.stream,   
  initialData: initData,   
  builder: (BuildContext context, AsyncSnapshot snapshot) {
        switch(snapshot.connectionState){
          case (Connection.active):
            setState(() { 
              data = data + snapshot.data;
            });
            break;
          default: 
            break;
        }   
      } 
)

If I do this, I get the setState() or markNeedBuild() was called during build.

How do I solve this problem?

1

There are 1 answers

0
Omatt On

Flutter StreamBuilder doesn't need to call setState to rebuild its children. StreamBuilder rebuilds by default when change were detected on stream. If no Widgets are needed to be rebuilt inside the StreamBuilder, you may consider initializing a Stream listener and append the new data when changes were detected on stream.