Blogs

Hive – An Easy, Fast, Secure NoSQL Database Implementation for Flutter Applications

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

  1. 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

  1. 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.
  1. For this project, we require a Task object for our To-Do App.
  1. Create a task object.

 

  1. ‘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.
  1. Open the terminal and generate the file by entering the following: Flutter packages pub run build_runner build
  1. To work with the generated TypeAdapter, we have to register the adapter in ‘main()’.

 

  1. 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

  1. Create a Change Notifier for the application.

 

  1.  After creating the notifier, register the ‘ListenableProvider’ in the ‘main()’.
  1.  And now we are ready to use this in our already created UI for the To-Do App.
  1.  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:

  1. https://pub.dev/packages/hive
  1. https://docs.hivedb.dev/#/ 
  1. https://medium.com/flutterdevs/hive-database-with-typeadapter-in-flutter-7390d0e515fa 

Leave A Comment

Related Post

Purpose to Contact :
Purpose to Contact :
Purpose to Contact :

Purpose to Contact :
Purpose to Contact :
Purpose to Contact :

Purpose to Contact :