Introduction
Coding without architecture will be so painful in this era. Especially there are many architecture pattern exists like Model-View-ViewModel, Model-View-Presenter, Model-View-Controller, etc. Architecture will make us easier to maintain our code and make the code more testable. Do you know flutter is also has an architecture pattern called BLoC? I will explain here.
What is Bloc
Bloc is a design pattern created by Google to help separate business logic from the presentation layer and enable a developer to reuse code more efficiently.
Why Bloc?
Bloc makes it easy to separate presentation from business logic, making your code fast, easy to test, and reusable.
When building production quality applications, managing state becomes critical.
As developers we want to:
know what state our application is in at any point in time.
easily test every case to make sure our app is responding appropriately.
record every single user interaction in our application so that we can make data-driven decisions.
work as efficiently as possible and reuse components both within our application and across other applications.
have many developers seamlessly working within a single code base following the same patterns and conventions.
develop fast and reactive apps.
Bloc was designed to meet all of these needs and many more.
Getting Started to Bloc example
Let's started to this example.
Today I want to make a sample of getting HTTP response API using bloc.
You can get the sample of API here
First step you need to create flutter project and define this on pubspec.yml
- http is for getting HTTP Response API
- flutter_bloc is for using Bloc library
- equatable is for overrides "==" and hashCode for you so you don't have to waste your time writing lots of boilerplate code.
Then you need to define API provider and API repository. This is used to follow clean architecture SOLID like on mobile native programming.
- Provider is for determine HTTP url used
- Repository is for communicating between provider and Bloc
Basically, Bloc is an event-state based architecture. So you need to define the state and event you want to use.
Event is for handling some actions and triggers from user or application (e.g onClickListener, onScrolling)
State is for knowing what states is on going, next, and exception in the application (e.g onLoading, onFailure, onResponseSuccess)
The key is on Api Bloc, every event will be trigger and sent to Bloc and processed and whether the process is done, bloc will emit to the state and ready to use.
Then on the widget you can use result the Api Bloc like this:
and provide bloc result using BlocProvider
and BlocConsumer
which can generate the API Bloc result state automatically when Api Repository is already emit every state based on network response condition.
Thank you and happy coding :)
full source is here
Top comments (0)