BLoC stands for Business Logic Controller. It was created by Google and introduced at Google I/O 2018. It is made based on Streams and Reactive Programming.
I can assure you that every intermediate-level Flutter developer in their development lifetime heard about Bloc or maybe tried to learn bloc. Bloc is one of the most popular state management choices among developers because it has rich documentation and is well maintained. But yes, there are some downsides as well, for example, a lot of boilerplate codes.
We will implement API integration at first, then persist the state so that when the user closes the app, it can maintain the state or load the data from the local device saved from the last API call to put it simply.
Note that after we kill the app, it starts right back where it left off. In addition, after it has loaded the previous (cached) state, the app requests the latest API data and updates seamlessly. Let’s get started!
Let’s add the necessary packages that we’re going to use throughout the application.
Copy the dependencies to your Pubspec.yaml file. I am using the latest version available now at this moment.
Then we need to install it with:
flutter packages get
You will get to understand everything as we go ahead.
We will implement the “FREETOGAME API”. For this, we have to make a datamodel of the API’s response. I have used the following website to make the datamodel class. It’s pretty easy, copy the JSON response and paste it on the website. The website will generate a class for you.
Website Link: https://ashamp.github.io/jsonToDartModel/
Don’t forget to tick the Null Safety checkbox!
Another datamodel that will contain the list of the games refers to the code below.
The above code will show you some errors, as you can see that the 5th line contains a code that indicates that this file is part of another file that needs to be generated. Another thing, look at the 7th line, it is indicating that we will serialize so that we can save the response for later use.
Open a terminal and run the below code.
flutter packages pub run build_runner build
It contains the logic behind the main bloc. Now we have to make the event and state as well.
There can be three(3) states.
- Game list is loading -> GamelistLoading
- Game list loaded -> GamelistLoaded
- Game list cannot be loaded -> GamelistError
We are calling the API using the HTTP package form from this file or class.
This portion contains the UI and the Bloc implementation. You can check the main function. It is instantiating the hydrated bloc in the temporary directory.
Note that after we kill the app it starts right back where it left off. In addition, after it has loaded the previous (cached) state, the app requests the latest API data and updates seamlessly.
You just integrated an API with HydratedBloc that has Caching.