Generally, when we are building a mobile application, we need to store some data locally on the mobile device. At that point, the Hive database comes into play. In this article, we are going to see how you can create a local database in Flutter using the Hive database. So, before we go any further, let’s begin…
- What is a Hive database?
- Hive database installation
- What are the boxes in the hive database?
- Advantages of hive database
- Operations in the hive database
- Conclusion
- Resources
What is Hive Database?
Hive is a lightweight, no-SQL database for Flutter and Dart applications. Hive is a great choice if you are looking for a straightforward key-value database with few relations. It is also extremely easy to use. It stores data locally on a mobile device. Bitcask inspires the hive database.
Hive Database Installation
Add the following dependencies in the pubspec.yaml:
What are boxes in the Hive Database?
There are boxes for storing all the data in Hive. The box is similar to a table in SQL, but it has no structure and can contain anything.
If the app is small, a single box might be sufficient. If you’re working on a more advanced problem, boxes are a great way to organize your data. You can also encrypt boxes to store sensitive information.
Advantages of Hive Database
- In comparison to SQFlite and SharedPreferences, it is faster in terms of speed and performance.
- Strong encryption built-in.
- Designed to support No-SQL databases
- It does not depend on any native libraries
- Easy-to-use
Operations in the Hive Database
First, we need to initialize the hive database in the main.dart file.
Create user model class (user_model.dart)
Create hive method class (hive_methods.dart)
Now create the home page screen (home_page.dart)
Here is the link to the github repo where you can download the code,
GitHub: https://github.com/sarfaraj-absyz/hive_database_operation.git
Conclusion
We saw how to integrate a Hive database in Flutter throughout this article. And also, we saw how simple, fast, and secure it is to integrate a Hive database into a Flutter application to store data locally on mobile. We hope you found this article useful in setting up a hive database in your next Flutter project.
Resources