What is Hive? How to use Hive in Flutter?

Tram Ho

What is hive?

Hive is a form of local database storage, Hive is organized as boxes. Each Box can be considered to correspond to an SQL Table, but it is data storage of unstructured form (NoSQL) ie type < key, value > and can store any data type.

Open Box in Hive

To use a Box, you must open the Box to use it.

This method is extremely useful in Flutter because it can be called anywhere without having to pass between widgets.

But if Box is already open, the above code will be disabled and the internal parameters will be ignored.

Once opened Box can proceed to Read, Write, Delete the elements in it.

The parameters that a Box will have are as follows:

Parameterdescription
nameThe name of the Box specified the storage location and is used to check if the box already exists.
encryptionKeyUsed to store encrypted and decoded data of Box but must be 32 byte array.
keyComparatorBy default, the keys are sorted alphabetically. This parameter allows you to provide a custom sort order of your choice.
compactionStrategySpecify your compression rule and Hive will compress according to that rule.
crashRecoveryIf your application is disabled while the write operation is running, the last item may be corrupted. This item will be automatically deleted when the application starts again. If you do not want this behavior, you can disable it.
pathBy default, the boxes are stored in the directory provided Hive.init () . With this parameter, you can specify the location where Box will be stored.
bytesYou can supply Box in binary form and open Box in memory.
EThe optional type parameter specifies the type of values ​​in the Box.

Read, Write, Delete in Hive

Read in Hive

Because the boxes in Hive use the <key, value> query type, just call the key to get the corresponding data:

If the key does not exist, it returns null. Optionally, you can specify the defaultValue to be returned in case the key does not exist.

Write in Hive

Writing to Box is like writing to Map <key, value>. All keys must be ASCII strings with a maximum length of 255 characters or unsigned 32-bit integers.

One advantage of Hive is that updates are instantaneous without the use of async in Flutter, and if you want to be sure to get data, you can add the await of the Future class.

With lazyBox if the get data fails, it will return null while adding await with future will return the old value.

Delete in Hive

Hive provides methods to implement Delete.

Hive in the simple Flutter app

I will write an app that features:

  • Add a new contact,
  • Delete contact by index.
  • Display saved contacts.

Add Hive library

Go to pubspec.yaml file and add the following paragraph.

Init Hive into the App

The hive needs to be initialized, indicating the path in which folder it stores data. It is best to initialize Hive right in the main()

And to prevent unnecessary data from loading on RAM when exiting the app, you should close () Hive again.

Create a Contacts class

Create a ContactPage Widgets where will display a list of saved contacts.

WatchBoxBuilder() is a Widgets of package flutter_hive used to update UI when there is a change of Box.

To add a new contact, create a new Widgets new_contact_form.dart

Because Hive requires to save data as Json, the contactsBox.add () method wants to do it, in the main() function, we have to add another Adapter .

Steps to create the Adapter:

Go to the Contact class and add annotations, HiveType will be for the class and HiveField will be for properties of that class.

Typing the following command to flutter will automatically generate an adapter file for us:

> flutter packages pub run build_runner build

As a result, we get a contact.g.dart file with the following content:

Finally build on your phone to test it:

So I have finished introducing Hive. Thank you to everyone for watching this hope that helped everyone.

Link code

https://github.com/nghiaptx-2124/HiveAppDemo

You can read more here:

https://docs.hivedb.dev/#/basics/hive_in_flutter?id=initialize-flutter-apps

https://resocoder.com/2019/09/30/hive-flutter-tutorial-lightweight-fast-database/#WatchBoxBuilder_Widget

Share the news now

Source : Viblo