Bloc is another state management library for flutter applications. B.Lo.C stands for Business Logic Component. Which takes ‘Event’ as input and produces ‘State’ as output. Bloc is built on top of RxDart. To understand some concepts, how to install, and how to use it in an application please check the video tutorial.
Source Code on GitHub
We can divide our flutter application architecture into 3 layers:
- Presentation or View Layer
- Data Layer
So basically Bloc stands between View and Data layers.
1. Data Layer
Its responsibility is to provide data from any source. Data Provider provides raw data and the repository is a wrapper of one or more data providers.
2. Bloc or Business Logic
Its responsibility is to receive events from the presentation layer and respond with a new state. It works as a bridge between the data layer and the presentation layer.
3. Presentation Layer
Its responsibility is to render itself based on one or more bloc states. It also handles user input and application lifecycle events.
Some Concepts for Bloc
Events are input to a Bloc. It’s a similar concept of like
action in Redux. In the presentation, layer events are generated by user interaction like a button click and passed to Bloc. An event may contain some additional data.
The state is part of the application’s state. It is the output of a Bloc. When a state changed, UI components will get the notification, and based on the current state it can re-render itself.
The change from one state to another is called transition. It holds the current state, event, and the next state.
Blocmust extend the base
Blocclass from the core
Blocmust define an initial state
- It must implement a function called
mapEventToState. This function takes incoming
eventas the argument. It also returns a
- To access the current bloc state we can use
- A bloc has a
Dispatchcan be called in the presentation layer or from within a bloc
onTransitionis called before a bloc state is updated
onErrorcan override to know bloc exception.
Here is the part of Bloc codes in the demo:
Step 1: Create Events
Step 2: Create a State
Step 3: Create Bloc
Step 4: Create BlocProvider in
Step 5: Use Bloc state and dispatch events