Using the BLoC pattern

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:

Futures and streams are two ways to deal with asynchronous programming in Dart. The difference is that futures have a single request and response, whereas streams are a continuous series of responses to a single request.

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.
For a strange choice of properties and class names, Stream (uppercase S) is the class that provides an asynchronous sequence of data, and stream (lowercase s) is the property of the StreamController where data comes out.

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.

You can also transform the data inside a Stream through an object called StreamTransformer—for example, to filter or modify the data. 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.49.247