Flutter Bloc Pattern

What is Bloc Pattern?

A Stream is an order of asynchronous events. Instead of getting the next event when you ask for it, the Stream tells you there is an event when it is ready. The Stream provides the means to receive a sequence of events. Each event is either a data event, referred to as an element of the Stream, or an error event, a notification that something failed. When a Stream has emitted all its events, a single “done” event will notify the listener that they reached the end. So simply we can say it is like an output.

You add streams of event/data input into a Sink and listen to them as streams of data output through a Stream. So in a simple term, It is an Input.

StreamControllers are manager objects that instantiate both a stream and a sink. It will work like a black box and do all the necessary works for you. There for this our processing.

How To Integrate Bloc Pattern in Flutter?

Let’s configure our bloc provider

Modify your bloc provider similar to this

It’s time for bloc configurations

Method 01 (With BehaviorSubject)

Once your bloc created, this method will call and define all the necessary data that you provide. According to this example, I assign 25 as my initial value for my age variable.
ageStream will give you the _age value as a stream
Here my target is to update age. So to achieve that, I create my update function which accepts the new age and assign the new age value to my age variable.
dispose method use to release the memory allocated to variables when state object is removed.
If you use single bloc inside your bloc provider and your static method is exactly like mine, choose this way
If you use multiple bloc inside your bloc provider, then choose this way

Method 02 (Without BehaviorSubject)

Here the _salaryStreamController is representing my variable and _updateSalaryStreamController is responsible for my updateSalary method which I am going to create in my future.
salaryStream method will return the _salary value as a stream and the updateSalary, gets an input and will perform some tasks. So it is declared as StreamSink (StreamSink is nothing but a Sink)
Here my target is to update salary. So to achieve that, I create my update function which accepts the new salary value and do the necessary calculation and assign the new salary value to my _salary variable.

Which method to choose?



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store