Flutter StreamBuilder Called Twice When Initialized Flutter StreamBuilder Called Twice When Initialized dart dart

Flutter StreamBuilder Called Twice When Initialized


Streambuilder will be called 2 times, first for Initial and second for the stream. And data is only changed when state is ConnectionState.active.kinldy see the official doc example.

    StreamBuilder<int>(  //stream:fire, // a Stream<int> or null  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {    if (snapshot.hasError) return Text('Error: ${snapshot.error}');    switch (snapshot.connectionState) {      case ConnectionState.none:        return Text('Select lot');      case ConnectionState.waiting:        return Text('Awaiting bids...');      case ConnectionState.active:        return Text('\$${snapshot.data}');      case ConnectionState.done:        return Text('\$${snapshot.data} (closed)');    }    return null; // unreachable  },);

StreamBuilder documentation

The initial snapshot data can be controlled by specifying initialData. This should be used to ensure that the first frame has the expected value, as the builder will always be called before the stream listener has a chance to be processed.

initialData

Providing this value (presumably obtained synchronously somehow when the Stream was created) ensures that the first frame will show useful data. Otherwise, the first frame will be built with the value null, regardless of whether a value is available on the stream: since streams are asynchronous, no events from the stream can be obtained before the initial build.


StreamBuilder makes two build calls when initialized, once for the initial data and a second time for the stream data.

Streams do not guarantee that they will send data right away so an initial data value is required. Passing null to initialData throws an InvalidArgument exception.

StreamBuilders will always build twice even when the stream passed is null.

Update:

A detailed technical explanation of why StreamBuilders build multiple times even when an initalData is provided can be found in this Flutter issue thread: https://github.com/flutter/flutter/issues/16465

It's not possible for a broadcast stream to have an initial state. Either you were subscribed when the data was added or you missed it. In an async single-subscription stream, any listen calls added won't be invoked until either the next microtask or next event loop (can't remember, may depend), but at any rate there is no way to get the data out the stream on the current frame. - jonahwilliams


As was said above, you just need to place your code inside Connection.Active state. See below:

StreamBuilder<QuerySnapshot>(              stream: historicModel.query.snapshots(),              builder: (context, stream){                if (stream.connectionState == ConnectionState.waiting) {                  return Center(child: CircularProgressIndicator());                } else if (stream.hasError) {                  return Center(child: Text(stream.error.toString()));                } else if(stream.connectionState == ConnectionState.active){                   //place your code here. It will prevent double data call.                }