Hive : The Fastest and Lightweight Database for Flutter
Hive is an offline and lightweight key-value database written in pure Dart with key-value coding. It is one of the fastest local databases available for Flutter, with read and write speeds up to 10x faster than SQLite. Hive is also very lightweight, taking up only a few kilobytes of space on disk.
What is the difference between Hive and SQLite ?
The main difference between Hive and SQLite databases is that Hive is better for analyzing complex data sets whereas SQLite is used for analyzing less complicated data.
Packages Used for the Hive
dependencies:
hive: ^2.2.3
hive_flutter: ^1.1.0
dev_dependencies:
hive_generator: ^1.1.3
build_runner: ^2.2.0
A Hive generator is for generating a path.
Import this package into your pubspec.yaml file to use the hive database.
The following commands will be used to generate the path:
flutter packages pub run build_runner build
Based on your annotations, this command is going to generate the appropriate data files for Hive.
How will Hive work?
Hive is organizing data into the containers. These containers are known as Boxes. To open a box in the hive use: Hive.openBox(‘boxName’);
These boxes store data in key-value pairs like a map.hive uses a tabular format to store and retrieve the data. We simply need to use the put function and give a key-value pair in that,
Something like this:
box.put(‘name’, ‘vidhi’);
You can also use the add method to store data. The add method will generate the key automatically. We need to only specify the value we want to store like this:
box.add(1);
You can store data of any data type provided by Flutter.
To get data we have to call a key like we do in a map. We can perform a crud operation via hive.
Initialization for Hive
First, you need to initialize the hive like this:
In your main.dart file initialize hive for your project.
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter(); // Open the ’employeeBox’
await Hive.openBox(’employeeBox’);
runApp(const MyApp());
}
What are the methods to use Hive?
For crud operation, we have some very easy-to-use methods.
- Put
- putAll
- Get
- Delete
- DeleteAll
- Contains key
1. Put:
The data is stored using put. Key-value pairs will be used to store the data. It will also be possible to update data on tables using put.
box.put(‘name’ ‘John’);
For updating data just add a new value to your existing key name: box.put(‘name’, ‘Johny’);
box.putAt(5,’Bob’)
//Add data at the index in case you have multiple data.
2. PutAll:
PutAll will store multiple data in key-value pairs at a time.
box.putAll({‘name’: ‘Erica’,’mail’: ‘erica@gmail.com‘})
//Add multiple data like a map
3. Get:
Get will simply fetch the data from the table. You can simply get the data with a key. The key will fetch the value for you and give its value as an output.
Ex: box.get(‘name’);
4. Delete:
It is possible to delete the data via the delete method. We can perform several operations for deleting like deleting a single key or multiple. Also, we can delete a record of particular indexes.
box.delete(‘name’);
// Delete a single record
box.deleteAt(5);
//Delete records of a particular index
5. DeleteAll:
DeleteAll will delete multiple data from a box by just giving key names like a list.
box.deleteAll([‘key1’,’key2’]);
//Delete multiple records by giving keys to the delete function.
6. Contains key:
Contains key will check if the key exists in a box or not.
box.containsKey(‘key 1’);
//checks key 1 exists or not
These are the basic methods you can use to store or retrieve normal data.
Now, we’ll explore how to save the entire API response in a Hive database and retrieve data using Hive.
For fetching data we have to create a model file to store and retrieve the API data. But while using the Hive, the model will be quite different from our normal model. As we already discussed, the hive will store data in a tabular form. So it will store data index-wise.
@HiveField(0)
int userId;
@HiveField(1)
String title;
You can see one more thing in the model class and that is
@HiveType(typeId: 0)
typeId: 0 is used to specify a unique identifier number for this particular class. Basically typeId will convert an object into bytes for storage. Also, type id will register an adapter for this class. TypeId will always be unique for each class.
How can You Create a Model?
You can see a part ‘post_model.g.dart’ here. This line is used for generating an adapter for this model. You can generate an adapter via this command:
flutter packages pub run build_runner build
If it shows any error then make sure that you have added
The hive_generator package in your pubspec.yaml file. This package will create an adapter automatically. It will generate one file named post_model.g.dart
Make a Function and Call Your API
This is what we call our normal API. Now we need to store API responses into Hive. For storing data first, we need to create a box like this:
Box box = await Hive.openBox<PostModel>(‘postBox’);
This line will create a box named postBox. You can give any name to create a box. Now we will store data in this box.
PostModel postData = await fetchData();
box.add(postData);
It will add our API response in the post box.
With this, we have successfully stored our data in the hive. Now, by using the get() method, we will retrieve the data from the hive.
PostModel? myData = box.get(0);
You can use a FutureBuilder to retrieve data from Hive and display it on the screen. To do this, simply invoke the fetchDataFromHive() function within your FutureBuilder.
Here is an example of fetching data from storage.
Why Hive is Better to Use than Shared Preference and SQLite Database?
Hive is better than shared preference because shared preference can only store data of type integer string double and boolean. Whereas hive stores complex data types like list and map and custom objects like API response.
The other one SQLite works in the same manner as Hive but the code complexity is less in Hive than in SQLite and is also very easy to use.
Hive is also better at performance than shared preference and SQLite. It’s an excellent choice for applications that require fast and responsive data.
What are the limitations of Hive?
There are some limitations to using Hive:
Does not Support Complex Relationships:
Hive can make it difficult to manage relationships between complex data sets.
Does not Support Complex queries:
Hive does not support complex querying.
Conclusion
Hive stands out as a fantastic choice for efficiently storing and retrieving data, thanks to its user-friendly methods and straightforward code. If you’re ever in need of expert guidance or support in harnessing the full potential of Hive, don’t hesitate to reach out to the dedicated team of professionals at Elsner Technologies. Their expertise is just a message or call away, ready to help you make the most of this powerful tool.