Reputation: 7919
Is StreamBuilder always called twice? Once for initial data and then once for the input stream?
Initializing the following StreamBuilder shows that the build method is called twice. The second call is 0.4 seconds after the first one.
Stream: Build 1566239814897
Stream: Build 1566239815284
import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:nocd/utils/bloc_provider.dart';
void main() =>
runApp(BlocProvider<MyAppBloc>(bloc: MyAppBloc(), child: MyApp()));
class MyAppBloc extends BlocBase {
String _page = window.defaultRouteName ?? "";
/// Stream for [getPage].
StreamController<String> pageController = StreamController<String>();
/// Observable navigation route value.
Stream get getPage => pageController.stream;
MyAppBloc() {}
@override
void dispose() {
pageController.close();
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final MyAppBloc myAppBloc = BlocProvider.of<MyAppBloc>(context);
return StreamBuilder(
stream: myAppBloc.getPage,
initialData: "Build",
builder: (context, snapshot) {
print("Stream: " +
snapshot.data +
DateTime.now().millisecondsSinceEpoch.toString());
return Container();
},
);
}
}
Why is the StreamBuilder called twice?
Upvotes: 7
Views: 8745
Reputation: 796
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.
}
Upvotes: 5
Reputation: 7919
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
Upvotes: 7
Reputation: 3898
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
},
);
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.
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.
Upvotes: 10