Hive in Flutter

Flutter Junction
CodeX
Published in
5 min readAug 4, 2022
Photo by Ante Hamersmit on Unsplash

Hive is the lightweight, NoSql, key-value database that is used to store the data locally in flutter and dart applications. There are numerous ways to store data locally. Hive can be used to store data for both mobile and web applications.

Our app works as follows:

Hive is very helpful and is very simple to utilize. It consists of the key-value database without numerous relations. Hive is the offline database.

All data stored in Hive is organized in boxes.

What are boxes?

Hive stores its data in boxes containing key-value sets.

For a small app, a single box might be enough. For more advanced problems, boxes are a great way to organize your data. Boxes can also be encrypted to store sensitive data.

Before using the box, the hive box needs to be opened first.

Open Box

var box = await Hive.openBox<DataModel>('hive_box');Or
var box = await Hive.openBox('hive_box');

Either way, you can open the box.

If the box is already opened, it is returned and all supplied parameters are ignored. Without opening the hive box, you cannot read, write, and delete the data.

Get opened box

A reference is stored by the hive to all open boxes. To get the data from the opened box, you can obtain it as follows:

var box = Hive.box('myBox');

This procedure or method is mostly useful for Flutter apps as you do not have to pass the box between the widgets.

Close box

In case, if you do not need the box again, you should close it. All the cached keys and values of the box will be dropped from the memory and the box file is closed after all read and write operations are completed.

You can leave the box open if you need a box again in the future. It is ok to leave a box open until the app is running.

await box.close();

Write

Writing to a box is very easy and is almost like writing to a map.

var box = Hive.box('box_name');box.put('name', 'John Doe');box.put('friends', ['Hari', 'Ram', 'Sita']);box.put(123, 'testdata');box.putAll({'key1': 'value1', 23: 'process'});

Read

Reading data from the box is very straightforward.

var box = Hive.box('myBox');
String name = box.get('name');
DateTime birthday = box.get('birthday');

If the key is not present, nullis returned. Optionally you can also a defaultValue that can be returned in the case the key does not exist.

double length=box.get('yourkey',defaultValue:12.5);

Lists returned get() are always of type List<dynamic> (Maps of type Map<dynamic, dynamic>). Use list.cast<SomeType>() to cast them to a specific type.

Type Adapters

Hive provides us permission to almost all primitive data types such as String, int, Map, List, DateTime and Uint8List. Type Adapters convert the object from and to binary form.

You need to generate the TypeAdapter or you can write on your own. You need to register the adapter before using it.

Register Adapter

You need two things to register the adapter, i.e an instance of adapter and typeId . typeId are unique and must be between 0 to 223. You can register an adapter as

Hive.registerAdapter(MyAdapter());

Why Hive Database?

  • It is the most efficient database in terms of speed and performance compared to other databases like SQLite and SharedPreferences.
  • It gives a straightforward method to perform CRUD operations.
  • Built-in strong encryption
  • No native dependencies

When to use Hive

Hive is very performant as it has little overhead compared to relational databases.

Hive can be used to store almost every sort of data.

  • Cart contents
  • Blogs/Articles
  • Messages
  • Categories of products
  • Session
  • etc

When not to use Hive

Every type of data can be stored in Hive when it is modeled in a correct manner. Sometimes it would be more convenient to use a relational database like SQLite as it is more convenient but because it is not faster.

You should consider using SQLite if your data contains complex relations and you have to rely mostly on indices and complex queries.

As Hive is so lightweight, you can use Hive and other databases together.

All right let's dive

Photo by Jeremy Bishop on Unsplash

Step 1: Create the flutter application

Step 2: Adding the dependencies

dependencies:
flutter:
sdk: flutter
hive: ^2.2.3
path_provider: ^2.0.11
hive_flutter: ^1.1.0
hive_generator: ^1.1.3

and dev dependencies too

dev_dependencies:
flutter_test:
sdk: flutter

build_runner: ^2.2.0

Step 3: Create a Model

We need to create model classes to work with the hive for the storage of data. We are going to make the Grocesories Memo app to store the needed groceries before going to market.

@HiveType will tell the information above the data model table which contains an argument typeId.

The @HiveFieldtells the data to pass for each property.

We have exented the HiveObject so as to get the key of our datamodel data item.

Step 4: Generate Adapter

To generate the DataModelApdater run the following command in the terminal.

flutter packages pub run build_runner build

It will generate the data_modal.g.dart

Step 5: Initialize Hive

You need to initialize the hive on the main method as it needs to be executed before other functionalities.

void main() async {
WidgetsFlutterBinding.ensureInitialized();
Directory directory = await pathProvider.getApplicationDocumentsDirectory();
Hive.init(directory.path);
Hive.registerAdapter(DataModelAdapter());
await Hive.openBox('hive_box');
runApp(const MyApp());
}

Step 6: Add Grocesories data

As we learned earlier, you need to have our box opening for adding data.

box = await Hive.openBox('hive_box');
DataModel dataModel = DataModel(
item: _itemController.text,
quantity: int.parse(_qtyController.text));
box.add(dataModel);

Step 7: Get Data

box = await Hive.openBox('hive_box');
var items = box.values.toList().reversed.toList();

Here we have used reversed to reverse our data so that new data gets on the top.

Step 8: Edit/Update Data

var box = await Hive.openBox('hive_box');
DataModel dataModel = DataModel(
item: _itemController.text,
quantity: int.parse(_qtyController.text));
box.put(itemKey, dataModel);

itemKey is the identifier of the data. Above we have extended the HiveObject so as to get this key.

Step 9: Delete Data

var box = await Hive.openBox('hive_box');
box.delete(items[index].key);

Let’s get connected

We can be friends. Find on Facebook, Linkedin, Github, Youtube, BuyMeACoffee, and Instagram.

Visit: Flutter Junction

Contribute: BuyMeACoffee

Conclusion

I hope this article is helpful to you and you learned new things. I have used various things in this article that might be new for some of you.

If you learned something new or want to suggest something then please let me know in the comment.

If you loved the article click on 👏 icon which provides motivation on delivering you all the new things.

Also, follow to get updated on exciting articles and projects.

Learning by sharing gives a great impact on the learning process and makes the community bigger and bigger.

Sharing is a magnet that attracts other enthusiasts toward you.

Hence, let’s take a small step toward making our learning community bigger.

Share this article with your friends or tweet about the article if you loved it.

Get full at:

--

--

Flutter Junction
CodeX
Writer for

Flutter Junction is a comprehensive learning platform offering a wealth of resources for developers of all experience levels.