Flutter Widget — StreamBuilder(Flutter- Async Programming with Dart) — Part 5

Abdur Mohammed
2 min readSep 19, 2022

--

Part of Flutter/Dart Shorts: To the point | Simple

1.0 Pre-requisites

2.0 Why is this Important?

Use cases include observing and reacting to:

  • Firebase data.
  • Sensor data.
  • Observing network connection status etc.

3.0 What is a StreamBuilder?

  • It will listen to the values flowing from the stream.
  • It takes in a stream and a builder method.
  • Whenever the stream emits a new value, it rebuilds its children.
StreamBuilder(stream: _customStream,builder: (context, snapshot) {/*build widgets*/});

4.0 Initial Data Property

  • We can provide initial data so that our widget has something to show while it waits for the first event from the stream.
StreamBuilder<String>(stream: _customStream,initialValue: 'Hello',builder: (context, snapshot) {/*build widgets*/});

5.0 The snapshot property

  • The snapshot parameter is an async snapshot.

5.1 The snapshot.connectionState property

  • You can check this property to see if the stream has not sent any data:
StreamBuilder<String>(stream: _customStream,builder: (context, snapshot) {if(snapshot.connectionState == ConnectionState.waiting)return Text('No data yet');....);
  • or if its already done
StreamBuilder<String>(stream: _customStream,builder: (context, snapshot) {....else if(snapshot.connectionState == ConnectionState.done)return Text('Yay Done!');....);

5.2 The snapshot.hasError property

  • As the name suggests, you can use it to check if there’s an error.
StreamBuilder<String>(stream: _customStream,builder: (context, snapshot) {....else if(snapshot.connectionState == ConnectionState.hasError)return Text('Oops! Failed');....);

or if everything goes well, handle data values as well

StreamBuilder<String>(stream: _customStream,builder: (context, snapshot) {....elsereturn Text(snapShot.data ?? '');....);

It is very important that our builder should know how to handle all the possible states of the stream. Once we have that, it can withstand whatever stream throws on us.

That’s all for this one. Next one is Async/Await :-)

You can find me on
LinkedInhttps://www.linkedin.com/in/knowabdur
Twitter: — https://twitter.com/AbdurDeveloper

--

--

Abdur Mohammed

React Native| Flutter | Senior Software Engineer | Sydney, Australia