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.
CodePudding user response:
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.
CodePudding user response:
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.