Which is efficient? Flutter StreamBuilder Widget vs Stream.Listen() with setState()
setState
does not rebuild the whole app widget tree. Both of the methods you mentioned (StreamBuilder & Stream.listen) rebuild themselves and their descendants whenever there is a new event.
If your whole app is under a single big build
method, then yes setState
will trigger a rebuild of whatever build
method it is under. If that is the case you should split up your code for performance reasons.
Your use case is actually mentioned in the official StatefulWidget docs.
Push the state to the leaves. For example, if your page has a ticking clock, rather than putting the state at the top of the page and rebuilding the entire page each time the clock ticks, create a dedicated clock widget that only updates itself.
Additionally, you can always look to take advantage of the devtools to measure any performance differences.
omer
Updated on December 29, 2022Comments
-
omer over 1 year
I am writing a periodic stream with duration of 1 second to show time:
stream: Stream.periodic(Duration(seconds: 1)), builder: (context, snapshot) { return Text(DateTime.now().toString()); }
Also, I can achieve the same with:
Stream.periodic(Duration(seconds: 1)).listen((){ setState(){});
as well.
I wonder, which approach is more efficient?
Stream builder returning a single widget or in other cases a widget tree every second. WhilesetState()
rebuild whole app widget tree in my case. I am confused here. Please advise.-
ambiguous58 about 3 yearsCould the devtools have a more precise answer?
-
omer about 3 years@pskink Seems now questions raises on using
StatefulBuilder
insideStreamBuilder
StreamBuilder will return StatefullBuilder each second. Also, Why we need to setState each seconds as I have already thosefields
in scope of StreamBuilder. anyways. open to discussion. -
omer about 3 yearsI do not want to avoid it but was curious about the performance of both method, (
StreamBuilder
vsStream.listen(setState(){})
) in my particular case. @ambiguous58 pointed out some useful hints below.
-
-
ambiguous58 about 3 yearsI don't think that's accurate since both of the methods OP mentioned (StreamBuilder & Stream.listen) rebuild themselves and their descendants whenever there is a new event.
-
Moaid ALRazhy about 3 yearsyes the descendants of the StreamBuilder in First case will be rebuilt , however in the second it calling setState() will rebuild the entire widget tree even above the widget thet needs to be rebuilt
-
ambiguous58 about 3 years
setState
only rebuilds thebuild
method it is under. So if the whole app is under a single bigbuild
method then yes it will be rebuilt. *shudder* -
omer about 3 yearsSo, using
StreamBuilder
seems equivalent todedicated clock widget
in this case. right? -
Moaid ALRazhy about 3 yearsyes this is what I meant exactly if you have maybe multiple stream Builders in column , then it would be better to use first method since it will build every one according to its state.