API Caching Using Hive and Bloc

Updated 15 December 2023

Save

API Caching Using Hive and Bloc.
In this article, we will see how we can cache API responses using Hive and Bloc.

API Caching Using Hive and Bloc

Hive is the lightweight,key-value database that is used to store the data locally in Flutter applications.
There are numerous ways to store data locally. Hive can be used to store data for both mobile and web applications.
For API caching hive is best suitable to use.

Bloc is a state management system for Flutter Apps recommended by Google developers. It helps in managing the state and making access to data from a central place in your project.

Read more about our Flutter app development services.

API Caching is used to make our mobile app response faster.
In this, article we are going to cache(save Api response locally)response using hive.
We will use the Bloc pattern for state management.

Dependencies

Let’s start by adding dependencies.

Create a Hive Model

Firstly, we will create a model class.
For example-

Create a Hive adapter:

Run the following command in your project directory to generate the adapter:

Initialize Hive and Register Hive Adapter

Inside main. dart file initialize hive and register adapter.

For example-

Hive Service class

Let,s make another class in which we define all methods related to the hive.
For example-

Basically, the addBoxes() function saves dynamic responses coming in API response.
So that we can use the same function at every place to add a box.

Ok. We have done with the hive part. Let’s move to another part of this article i.e. Bloc.

State Class

Firstly, we create a class for bloc States.

Event Class

Repository Class

Create a class which in which we will define functions to get data from Db or Server.
For example-

Bloc Class

Finally, we will create a Bloc class. Which is the main class of bloc pattern.

Now you can call the event from your widget class.
When an event will be triggered it will check the data in DB.
If data is found then it will display on the screen and in the background API will hit to get an updated response from the server.
If there is any updated response comes then it will update the DB and screen as well.

Etag– We are using etag variable to sync App-end db data with server-end data.

Conclusion :

This is how we can manage or enhance app performance and provide a seamless user experience.

Thanks for reading this article.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • DanBi
    • Pankaj Tyagi (Moderator)
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home