When using the BLoC pattern, everything is a stream of events.
A BLoC is a layer between a source of data in your app and the widgets that need the data—for example, the source might be an HTTP response from a web API or a query result from a database, and the widget might be a ListView that receives the data.
The BLoC receives streams of events or data from your source, deals with the business logic, and returns or publishes one or more streams of data to widgets that listen or subscribe to them.
A simple diagram of the role of a BLoC is shown in the following image:
A BLoC has two components, sinks and streams, both of which are part of a StreamController.
You could think of a stream as a pipe. This pipe has two ends: a way in and a way out. It's a 'one-way only' pipe. When you insert something into the pipe, it enters by the Sink, possibly being transformed inside (if you want it to be), and then exits from the Stream.
You should bear in mind the following facts when using the BLoC pattern in Flutter:
- The pipe is called a Stream.
- To control the stream, you use a StreamController.
- The way into the stream is the sink property of the StreamController.
- The
- way out of the stream is the stream property of the StreamController.
In order to use the Stream and be notified when something comes out of it, you need to listen to the Stream. You define a listener with a StreamSubscription object.
The StreamSubscription is notified every time an event related to the Stream is triggered—for example, whenever some data flows out from the stream or when there is an error.