Hive Database with Type Adapter In Flutter 

   Hive is a lightweight and blazing fast key-value database written in pure Dart.
we can use hive for large data storing because it support custom models in a very easy way.
in this blog post we are going to register our custom model class in hive database and perform crud operation.

let take the example of saving registered user data using our custom model.
and look into changes in data on user profile screen.

how to use hive database in flutter, use hive  type adapter in flutter, use custom adapter in hive flutter,


Let's Begin. ⌚

what we need:

1. hive_flutter
2. hive
3. hive_generator
4. build_runner 

add the above packages in pubspec.yml file.

NOTE. the 3 and 4 packages should be added under dev_dependencies as shown below.


use hive in flutter



















now let create our model class shown below.

in this image we see how to create a hive custom adapter














now let's explain what we did in our model class.

part. we are passing a string which will be our hiveAdapterClass name
         the name should be same otherwise your adapter class will not be
         generated.

@HiveType.  we are passing 1 here this should be unique for every model class  
                       across app.

@HiveField(num).  this number should be unique for every field across model class.

after writing our model class we need to run the following command for generating the adapter class.

command: 
flutter packages pub run build_runner build

your generated adapter class will look like the following.

this image contains the code for custom model adapter of hive database


















now we just need to register our ModelAdapter class  and open a box of type UserModel (model class name) 'users' is the key of our box in 3 line same as following.

but before doing that we have one extra step add path_provider package to get path for storing data.

this image contains the code for registering custom hive adapter in flutter, custom adapter in flutter hive


now we are ready just add the model class object to our database from where you want.
I will implement the logic by clicking the floating action button.
and will show the user data from database.

Add User Object.
 
for storing data we need to open the box by passing the boxKey in our case 'users'.

how to insert data in hive database, how to add custom adapter in hive flutter










Show All Data From Database.
 
we will implement the logic where we can continuously listen to changes made from anywhere .

let see the last step.


read data from hive database i flutter


all set.

NOTE.  if you are changing any thing in model class just delete user adapter class and then run the command to skip any type error.






Comments