Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Performance - SetState vs StreamBuilder

Tags:

flutter

In Flutter, which way has the more performance over high load handling?

Let's say that we are listening to a stream which emits around 1000 msgs per second. Which way will have more performance?

1) Using setState() like

stream.listen((msg) => setState(() => _msg = msg)

then in the build method

return Text(_msg);

2) Using stream builder

StreamBuilder(
              stream: stream,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Text(snapshot.data)
                  );
                }
              },
            )),
like image 471
Kavinda Jayakody Avatar asked Oct 22 '25 15:10

Kavinda Jayakody


1 Answers

According with flutter docs:

When setState() is called on a State, all descendent widgets will rebuild. Therefore, localize the setState() call to the part of the subtree whose UI actually needs to change. Avoid calling setState() high up in the tree if the change is contained to a small part of the tree.

Therefore in your particular case may you will haven't performance differences, however in large widget trees StreamBuilder will isolate your widget avoiding rebuild in entire tree.

I also recommend you to check you specific scenario with "DevTools Widget Inspector Page". It will give you a real time analysis, including GPU time, memory consumption, performance and much more.

like image 109
Cassio Seffrin Avatar answered Oct 24 '25 10:10

Cassio Seffrin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!