Skip to content
DeveloperMemos

Hive Tutorial(Flutter)

Flutter, Dart, Database, Hive2 min read

Today I thought I'd write a quick tutorial about Hive, a key-value database solution for Flutter. I have been following Hive for a while now and have also used it in a really simple production app without any major issues so far. In this post I'll quickly show how to install and read/write with Hive. I'll also write a little about why you may and may not want to use it.

Reasons to use Hive

There are a couple of reasons you might want to use Hive in your project:

  • It is fast(check the benchmarks on the repo).
  • It is pretty easy-to-use, you won't have to think up or write any SQL statements.
  • It is pure dart, so it will run on Flutter Web/Desktop too without any hassles.

Reasons to avoid Hive

Here are some reasons that you might want to opt for a different solution instead:

  • There is no query support(yet).
  • Apparently it isn't meant for really large data-sets.
  • There is an element of lock in. If for some reason you want to switch from Flutter back to native you might have to go through some hassles to port your database back over. You wouldn't really have these issues if you used something like SQLite.

Installing

To add Hive to your project first you need to add the following dependencies to your pubspec.yaml file:

1dependencies:
2 hive: ^1.1.1
3 hive_flutter: ^0.2.1
4
5...
6
7dev_dependencies:
8 hive_generator: ^0.5.2
9 build_runner: ^1.7.0

The versions used above are current as of the 6th of December 2019. Make sure you check the repo to ensure you're using the latest versions.

Initializing

Before you read/write any data you need to initialize Hive using the init method and specify a directory to save the database files to. You're probably using Hive for Android or iOS development, and if so you're going to need to install path_provider as well. Once you've installed path_provider, you can initialize Hive and open a box for your data using the documents directory:

1final dir = await getApplicationDocumentsDirectory();
2Hive.init(dir.path);
3_box = await Hive.openBox('app_data');

Reading and Writing Data

Once you have a box open it's ready to use. You can write data to a box using a key, like this:

1_box.put('name', 'Greg');

And you can read data using the get method like this:

1_box.get('name');

Unlike the openBox method put and get are synchronous. As far as data types go, the sky is really the limit because Hive supports all primitive dart types aswell as List, Map, DateTime and Uint8List. You can also store objects using something called TypeAdapters.

And that's really all that needs to be said about the bare basics. If you want to use Hive for handling state I suggest combining it with something like Provider. Or if you're looking for an alternative with query/SQL support I have personally used sqflite in production for a while now without any problems.