My First Journey to a BLoC Planet | BLoC For Beginners

Roshdy Nehru
CodeX
Published in
6 min readJun 6, 2022

--

Set state will no longer serve you as your project grows larger, so I start my spaceship’s engine and prepare for my journey to State Management Galaxy, we will land on plant called BLoC, previously i visited his moon called Cubit.

When we landed on the planet, we discovered that the inhabitants there working in some sort of flow.

this how BLoC works we create events to trigger interactions with the app then bloc sends the replay by emit states.
we will discuss this better with code in our two projects that we will code using Bloc

Counter Application

The first application to start with,We will refactor the default flutter application to understand BLoC with simple and easy way.

Counter Application final Result

Project structure

├── lib│   ├── utils│   │   ├── app_observer.dart│   ├── counter_bloc│   │   ├── counter_bloc.dart│   │   ├── counter_event.dart│   │   ├── counter_state.dart│   │   └── view│   │       ├── counter_page.dart│   │       └── counter_screen.dart│   └── counter.dart│   └── main.dart├── pubspec.lock├── pubspec.yaml

It requires to put oil for our spaceship and supplies in our bag to help us during our journey,I am going to tell you everything you need which known as Packages.

bloc

flutter_bloc

equatable

http

flutter_rating_bar

Starting with main.dart

then create view/counter_view.dart

our screen contain two Floating action Button and Text widget for our counter, but when we click on any of the two buttons nothing happen and our widget is stateless so we Can't do anything to change state,so we need to ask for help from BLoC.

First, we need to create counter_bloc/counter_event.dart

the bloc need events to trigger interact on the view class so we have two types of interacts, first one when the user press button to increment the counter value and the second one to decrement value.

Event inform bloc what user needs to increment or decrement counter value then bloc need to emit states as the results of events happened

the next step is to create counter_bloc/counter_state.dart

we need to extends counterState class with all possible states that could happen.

CounterInitial initial state where we start the counter with it’s initial value

CounterSucessState when counter value increment or decrement successfully

CounterErrorState to handle error that could happen

Finally, we can reach our last step on making BLoC do it’s work we need to create counter_bloc/counter_bloc.dart

i initialized count with his initial value = 0 , then we need to use event and states together to complete our recipe.

we would start with mapping events to state,get events and bloc emit state based on the result, If the user attempts to decrement the counter value to a negative number, the bloc will emit an error state.

Finally, we will start working with view to link bloc with view to do some magic.

create view/counter_page.dart

we will use it to Provide bloc to our view using BlocProvider.

then we need to go back to counter_view.dart

we will wrap our view widget with BlocConsumer.

BlocBuilder we are using it to build widget based on what is the current State.

BlocListener we are using it to keep listening for new changes in the state.

BlocConsumer with it we can use both to listen and build.

context.read<CounterBloc>().count;

to read counter inside bloc

context.read<CounterBloc>().add(IncrementCounterValue());

Notifies the counter bloc of a new increment event

And that’s the last step on our counter application adventure we will travel to start with another adventure of making movies application stay tuned.

IMDb top rated Movies Application

During our journey in space of coding we met new thing, it’s Called API, he knows some information that we would need.

so in movie application we will work with it, we will get data from it.

Top rated movies application [‘Final result’]

UI isn’t our big deal so i didn’t give it much attention

We already understood how to work with BLoC from the last application, so we can skip some explanations, but in this application, our bloc will have to do some more work.

There is something new from the old work flow, Bloc have new friend called data to say hi to him and request data the events inform Bloc about it, then our new friend will response with the data or apologize that he couldn’t get it.

First and foremost, we must determine what type of data we require from API in order to develop our Movie model.

After that we can fetch data from API service

You need to get your key from TMDB

We’ll start working with our BloC after we finish the data phase and acquire the repository’s List of movies through API Services.

Starting with BLoC

I simply need one event to notify BloC to Start getting movies operation.

Our state class differs from the counter state class; I found that style of coding to be easier if there are numerous changes; I simply use copyWith to emit state to new state based on BloC response.

We have one event to map it to states; if we successfully get a list of movies, we will change the state status from loading to success; otherwise, we will emit an error state.

Starting with View

When we start our application, the first thing we need to do is collect data and provide it to the bloc, so we return RepositoryProvider to tell the repository to go and begin working.

Because there are three possible states, Bloc builder will create a widget dependent on the state status.

State is success : Bloc builder reutrn MovieSuccessWidget().

State is Loading : while waiting for fetching data the application will display circular Progress Indicator.

State is Error: return CustomErrorWidget().

We’ll start with the simplest task and work on ErrorGettingMoviesWidget.

This is how our widget would look if there was a data catching error.

If there were no errors and the state status was success, we would have our movie list in hand, and we would represent the data as a GridView.

MoviesCard allows us to customize how we display each movie and its attributes.

Finally we need to track our bloc and know what is his current station to be easy for us to handle error and trace our code so we will create something to be our eyes it’s called bloc observer.

It wants to be in the main function in order to carry out its duties.

We must make changes our main.dart to be look like that

We can easily trace our bloc movements, as shown in the following Picture.

In the previous image, the bloc begins with the initial state, then moves to the loading state until we successfully retrieve data from the repository, at which point the bloc emits the success state.

Our journey on the planet has come to an end; see you in the next adventure.

Our entire journey is documented here.

https://github.com/NehruJr/Flutter_BLoC

I hope you found my article helpful , thank you for your time.

--

--