Purpose of the article: To educate beginners and flutter developers to work with the Hive DB for local storage of the application data
Intended Audience: Flutter Enthusiasts
Tools and Technology: Android Studio, Flutter SDK
Keywords: Local Database, Hive, Flutter, Storage
Hive is a dart package used in Flutter applications for storing data locally and manipulating the data on a targeted device. Among several existing packages (Example: Floor, Moor, sqflite), Hive stands out to be very fast in CRUD operations, and at the same time, it stores the data securely using AES-256 (a robust encryption standard) encryption. This way, we can replace the dependency on popular flutter traditional packages like ‘shared_preferences’ and ‘flutter_secure_storage’ both at once.
In this post, I will explain the implementation and demonstrate the usage of the package in a To-Do application.
Add Dependencies
- Go to your project directory and the below in ‘pubspec.yaml’ file
dependencies:
hive: ^2.0.4
hive_flutter: ^1.1.0
dev_dependencies:
hive_generator: ^1.1.0
build_runner: ^2.0.6
Creating and registering a Type Adapter
- Hive can store data using dart primitive types, although in production, we deal with model objects; to deal with objects, we need to generate TypeAdapter.
- For this project, we require a Task object for our To-Do App.
- Create a task object.
- ‘typeID’ is the identity of the object for the Hive to find it. HiveField must be annotated on the required field names, with their unique id in parameters.
- Open the terminal and generate the file by entering the following: Flutter packages pub run build_runner build
- To work with the generated TypeAdapter, we have to register the adapter in ‘main()’.
- After registering, we can use the power of the provider package for state management of the app, and Hive works with the provider efficiently.
Creating Change Notifier
- Create a Change Notifier for the application.
- After creating the notifier, register the ‘ListenableProvider’ in the ‘main()’.
- And now we are ready to use this in our already created UI for the To-Do App.
- Clone the below Git-Repository to review the whole project.
https://github.com/abhishekgokavarapu-abzy/mt_todo_app.git
Demo Gif of App
References/ Sources: