Hive Database in Flutter: Store and Retrieve data Locally

Raju Potharaju
GYTWorkz
Published in
6 min readMar 27, 2023
Blog Banner

Flutter is a popular mobile application development framework that allows developers to create high-performance applications for both Android and iOS platforms. When it comes to data storage in Flutter, there are several options available such as SQLite, Shared Preferences, and Hive.

Hive is a lightweight and fast NoSQL database that can be used to store data in Flutter applications. In this blog, we will explore how to setup and use Hive database in Flutter.

In this article, we’ll go over these steps to build a simple CRUD app that stores cats data with hive:

  • Setup Hive
  • Type Adapters
  • Storing data
  • Reading data
  • Update and Delete data

So let's get started! OKE?

Before we begin with Setting up Hive, we need to set up our Flutter project, which I already did, and put it in the lib/hive_db_blog folder in my Github repo, it contains the UI and the provider setup. You can clone it from there.

Hive Implementation UI

Step 1. Setup Hive

To use Hive in Flutter, we need to add the following dependencies to the pubspec.yaml file:

dependencies:
hive: ^2.2.3
hive_flutter: ^1.1.0

we also need to add hive_generator and build_runner to the dev dependencies:

dev_dependencies:
hive_generator: ^2.0.0
build_runner: ^2.3.3

Next, we need to initialize Hive in the main() function of our Flutter application. We can do this by calling the Hive.initFlutter() method as shown below:

void main() async {
await Hive.initFlutter();
runApp(const MyApp());
}

Step 2: Define Hive Type Adapters

Hive is a NoSQL database that stores data in key-value pairs. Where value can be of a different type such as int, string, list, or custom objects. To store custom objects in Hive, we need to define type adapters that tell Hive how to serialize and deserialize our objects. We can use the hive_generator package to generate type adapters for our custom objects automatically.

This means we will create a model class and store that entire modal in Hive. My model class is called as cat_model.dart

class CatModel{
final String name;
final String age;
final bool isMale;

const CatModel(this.name, this.age, this.isMale);
}

It's a simple model class. let's make it compatible with Hive by tweaking it a little.

import 'package:hive/hive.dart';
part 'cat_model.g.dart';

@HiveType(typeId: 0)
class CatModel {

@HiveField(0)
final String name;

@HiveField(1)
final String age;

@HiveField(2)
final bool isMale;

const CatModel(this.name, this.age, this.isMale);
}
  • Annotate the model class with @HiveType(), so the generator knows this should be a TypeAdapter.
  • Annotate each field you want to save with @HiveField(index), the index is an int and each index should appear once and you shouldn't change it after registering them.
  • In case you change the field name or its datatype or add a new field — You have to run the type adapter command again and re-run the app to reflect the changes in the app.

We can then generate the type adapters for this class by running the following command in the terminal:

flutter packages pub run build_runner build

This will generate a cat_model.g.dart file that contains the type adapter for our CatModel class.

Finally, register the type adapter in your main function, just add it beneath your hive initialization.

void main() async {
await Hive.initFlutter();
Hive.registerAdapter(CatModelAdapter());
runApp(const MyApp());
}

Step 3: Storing Data in Hive

To store data in Hive, we need to open a Hive box. A box is similar to a table in a traditional SQL database and stores key-value pairs. We can open a box by calling the Hive.openBox() method and passing in the name of the box as a parameter. For example, we can open a box named cats as shown below:

Hive.openBox<CatModel>('cats');

We can open the same box multiple times, returning us the same box instance. However, it is good practice to open it once on app launch and get the box whenever we want to add/update/delete data from it. To get the cat box, we can do the following:

Box<CatModel> catBox = Hive.box<CatModel>('cats');

And there are 2 ways to add data

  • box.add(value) - just gives each value an index and auto increments it.
  • box.put('key', value) - you have to specify the key for each value

Now we can add data to it by creating a new instance of the CatModel class. and add it to Hive database using put() method

For example, we can add a new cat to the box as shown below:

var catModel = CatModel('foo', 4 , true); //creating object
await catBox.put(catModel.name, catModel); //putting object into hive box

In this example, we have added a new cat with a key same as its name foo to the catBox box.

Step 4: Reading Data from Hive

There are different ways to read data from your boxes:

  • box.get('key) - get the value from a key.
  • box.getAt(index) - get the value from an index created with box.add().
  • box.values - this returns an iterable containing all the items in the box.
CatModel? catModel = catBox.get('foo'); //get by key
CatModel? catModel = catBox.getAt(3); //get by index
List<CatModel> catModelList = catBox.values.toList(); //get all items in list

We will use the third method to get all the cats that we have added so far.

Step 5: Updating Data in Hive

To update you can use box.put('key', newValue) to update that value, or box.putAt(index, item) which works like getAt()

for example, let us update the age of our previous cat foo

var catModel = CatModel('foo', 5, true); //creating new object 
await catBox.put(catModel.name, catModel); //putting object into hive box

When we put in a new model with the same key, the old data gets updated.

Step 6: Deleting Data from Hive

Deleting items is similar to getting:

  • box.delete('key) - delete by key
  • box.deleteAt(index) - delete by index
  • box.deleteAll(keys) - accepts an iterable of keys, and deletes all the keys given.
Box<CatModel> catBox = await HiveBoxHelperClass.openCatBox();
await catBox.delete('foo'); //delete cat with key (name) as 'foo'

Hurray!, we have successfully completed our ‘C’ ‘R’ ‘U’ ‘D’ in Local database.

Conclusion

Hive is a lightweight and fast NoSQL database that can be used to store data in Flutter applications. In this blog, we have explored how to set up and use Hive in Flutter, including defining Hive type adapters, and storing, reading, updating, and deleting data from Hive. By using Hive in our Flutter applications, we can easily store and retrieve data without the overhead of traditional SQL databases.

--

--

Raju Potharaju
GYTWorkz

Software Engineer with 3 years of experience building beautiful and complex Applications | Loves Teaching | Talks about Flutter, React, Python and Java