Which is efficient? Flutter StreamBuilder Widget vs Stream.Listen() with setState()

Viewed 935

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. While setState() rebuild whole app widget tree in my case. I am confused here. Please advise.

2 Answers

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.

I think First approach is more efficient because when event comes it will only trigger the build of that stream .

however calling setState() will rebuild the entire widget tree of the stateful widget .. so it costs more

Related