What is BLOC patten in flutter? - flutter

I'm trying to understand the bloc pattern but unable to understand.
Browsed many tutorial but couldn't understood properly. I just understood that
bloc pattern is used to managing the state of app. and
for take input, use sink and for output, we use Stream by stream controller.
and not sure I'm getting wrong or right.
But clear thing is that, it's not enough for acquaintance of bloc pattern.
Explain it with simple language.

The Business Logic Component (BLoC) pattern is a pattern created by Google for state management.The BLoC pattern uses Reactive Programming to handle the flow of data within an app.
A BLoC stands as a middleman between a source of data in your app (e.g an API response) and widgets that need the data.
A BLoC has two simple components: Sinks and Streams. Input of BLoC is sink and output is stream.
User inputs are given to the BLoC by adding data to the sink --> business logic is in the bloc which processes data --> Widgets listening to the streams will be notified with the processed data.
In other words, it receives streams of events/data from the source, handles any
required business logic and publishes streams of data changes to
widgets that are interested in them.
Here is a wonderful article that has an example that you can refer to understand BLoC better.
BLoC can be implemented using StreamBuilder and StreamController but you should use flutter_bloc flutter package to cut the boilerplate code. examples.
I hope this helps, in case of any doubts please comment. If this answer helps you then please accept and up-vote it.

it is a way to communicate between your logic and UI and change the UI base on your logic or vice versa
in flutter, you will need to change your widget's (User interface) base on the some logic for example if user clicks on the A show the B text the or vice versa for example if year is 2020 show 2020 text to user bloc is just a pattern that helps you to accomplish this (whit some positive and some negative points) and there are lots of patterns other than bloc that will do this job for you
you could study about state and what is state management and why we need it? in the state management section of the flutter documents
link here:
also bloc library official documents are a good place to start learning about the bloc.
link here :

Bloc makes it easy to separate presentation from business logic, making your code fast, easy to test, and reusable.
Bloc attempts to make state changes predictable by regulating when a state change can occur and enforcing a single way to change state throughout an entire application.
You can read more here, it is easy to understand

BLOC is another state management pattern used by many for flutter and angular.
In simple words it allows you to update specific widgets when some specific state is declared by the bloc. You can dispatch an event to change the state of the widget which is wrapped with BlocBuilder.
For doing some process other than building widgets, you can use BlockListener and do the process you want based on the state declared by the bloc.
You can learn more about it here: https://bloclibrary.dev/#/gettingstarted

Related

Why Do we Use Bloc In projects?

I've been coding with dart and flutter for over a month now, one thing that I was recommended to do by my friend is to learn Bloc as it would be helpful for big projects for businesses. From watching Videos on Youtube, reading documentations on it and also looking at Github repo's I've still not understood why we need to use Bloc and its features (FYI: I've only started using Bloc the last 2 days') Would appreciate if someone would explain what's the purpose of using Bloc as opposed to just normally coding.
Benefits of using Bloc pattern
It follows SOLID principle.
Your business logic is decoupled from the UI.
You can use same Bloc object in various screens. For example if you are developing e-commerce app, you might want to show cart icon with items added on many screens and items could be added to cart from any screen, you don't have to pass around Cart object or Function to addToCart.
You instantly get notified when Bloc state is changed and you can build your widget based on new state. This also handles unnecessary builds.
You can change any implementation of business logic (like form validation) in the bloc and your UI will not need any change.
Adding Analytics to the app is also convenient.
Less logic in Widget classes means easier readability.
You can transform events passed to Bloc. (in case if you are showing search bar and on every letter type, you are making a network call to show search suggestion, you can add debounce to certain time).
You don't have to check for Authentication in every screen.
You can respond independently to various state changes of Bloc for showing Snackbar/Toast in any screen.
Less number of items passed while creating widget class (as many properties can be accessed from Bloc object)
Follows MVVM pattern which says model, viewmodel and view should be independent of each other so that future modifications/ scaling/ debugging is easier.
There could be many more benefits which others can tell. You will only realize them once you would have started using the Bloc after working with a project which does not have state management.
Sidenote: flutter_bloc library is an option to implement Bloc pattern. Bloc pattern was showcased by Google and you can write your own implementation as well. But the flutter_bloc library is very robust.
BLoC or any state management protocol will only help you to separate data and presentation layer in your project. It will prove useful when a company has to grow its tech team or if they are planning to separate front-end and back-end development.

Does The Bloc Pattern Include State Management?

This may be a noob question but I am new to Flutter. Hearing all those keywords: "State Management, Provider, Redux, MVVM and Bloc", I get a little bit confused.
When implementing the Bloc pattern, is it that you already implemented state management? Does this (in most cases) mean that I do not need to use another tool like Redux or Provider? To get a better idea, I am going to build a mobile webshop using Flutter and the Woocommerce package.
If I understand correctly with the Bloc pattern you have the follow:
UI screen (view)
BLOC (ViewModel, including functions such as getting data or updating data or deleting data)
Repository (Get's data from an API)
Network Provider (the api itself)
If it's not complete, feel free to add an extra explanation.
Hope anyone has clear answers!
Cheers
When implementing the Bloc pattern, is it that you already implemented state management?
Yes indeed.
Does this (in most cases) mean that I do not need to use another tool like Redux or Provider?
You can use them, but personally, I see no need when I already use BLoC and would not mix them.
Yes bloc itself is a state management tool in flutter and there is no need to use any other state management tools along with it.
Though it can be done but try to use single state management for whole app so that mismatch doesnot happen .
Also Bloc makes sure to preserve the state and update it when necessary. That is what state management is !

Manage state for nested classes using Flutter Provider

Currently am working on Sport Event Scoring app.
The structure of the app goes something like this:
Right now I am trying to include state management using provider package.
Scoring occurs at the very bottom of the Widget tree using a counter and each Widget initializes respectively named model based on a user input on the go - creating Event, adding divisions and players each happens in a dialog.
I know I need to create a provider for list of Events, however, I am not sure how to go about structuring rest of the state management. So far I tried turning each model into a Provider by mixin in the ChangeNotifier and moving all the methods which change the data inside where the state would be managed as well with notifyListeners().
However after a lot of struggling and searching I found that it's not the best approach to manage the state inside models.
What approach would be ideal?
Should I manage the state through the Event List provider, or should I go with creating a provider for each model in a separate file? If so, how?
I am not too sure about the full scope of your project nor how far you are into it but I would highly suggest checking out the BLOC library as an alternative state management solution to simply manage the state in your case.
The learning curve is fairly low with many tutorials on how exactly to use the library alongside the fact that BLOC is much less reliant on listeners from an external persons view using the library from my experiences if that is what you are struggling with.
Here is a link to the BLOC Library
If you are still persistent to use Provider, I would suggest you create a provider for each model in a separate file for multiple reasons such as separation of concerns and ease of management of state and clarity of each different model.

How to limit Flutter bloc creation

I have an application which required the writing of many blocs.
Several pages use the same bloc. For example, messaging pages use the MessagingBloc.
Currently, I use a global multi-provider to dispatch blocs to child widgets. The problem is: when I change pages (so I no longer use the messaging feature), the bloc is, logically, still present in the tree structure.
Do you know a way to have in the tree, only the blocs that are currently in use? (maybe working with one Navigator by feature but it seems too complicated/expensive)

Passing data to a slider

I'm working on a prototype for a storefront, and I have a slider where I have the option to see the user's profile. Every user has to register first before they can access the store (is just a prototype).
When a new user registers successfully, they will be immediately sent to the product catalog screen. On the same catalog there will be a slider, and in that slider there will be an option to see the user's profile page.
My question is, how can I send the user's info (name, email and phone number) through the catalog page, then trough the slider, and then to the user's profile page?
I already have a class that holds the user's info that's created on the RegisterPage class/screen.
Unless I'm reading the question wrong, it sounds like some kind of state management solution would be useful here. That is, once you know the user's details, they should be stored in a place that is easily accessible later on from other widgets.
There are a few state management options available:
StatefulWidget - a classic, simplest approach. Have a StatefulWidget which tracks state (user's details), and pass them down the widget tree to a component that can make use of those details. Gets a little unwieldy if you have a deep tree and need to pass the data down through several layers that don't really care about said data.
InheritedWidget. Propagate information down the widget tree and rebuild UI whenever inherited widget itself changes state. Relatively straightforward, simple solution. Unlike StatefulWidget, you can retrieve required data where you need it, and you don't have to pass it down as arguments to yet another widget.
Provider package. A state management solution by Remi Rousselet, endorsed by Google itself. Easy to use and understand, and quite scaleable. Advertised as:
A mixture between dependency injection (DI) and state management, built with widgets for widgets.
Redux. Another state management solution that comes in a form of a package. If you've worked with React/Redux, you will feel right at home. It's not as full-featured as its JavaScript counterpart, but the idea is the same: have a store to which some widgets are listening, and rebuild them whenever data changes.
BLoC / Rx. One of the Google's recommended ways to manage state. Leans heavily on streams. Is somewhat more complex to understand, but rather powerful once you do.
MobX. Another state management solution ported from JavaScript world. I haven't had much experience with it, but I believe it's based on observables, actions and reactions. I expect it should be quite similar to JavaScript's counterpart.
You can read more about each of those by heading over to the dedicated page on the official documentation.
Personally, I'd probably choose something relatively simple first - perhaps InheritedWidget or provider package. However, it heavily depends on your use case and what programming paradigms you're comfortable with / want to experiment with.