— Flutter, Dart, Database, Hive — 2 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.
There are a couple of reasons you might want to use Hive in your project:
Here are some reasons that you might want to opt for a different solution instead:
To add Hive to your project first you need to add the following dependencies to your pubspec.yaml
file:
1dependencies:2 hive: ^1.1.13 hive_flutter: ^0.2.14
5...6
7dev_dependencies:8 hive_generator: ^0.5.29 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.
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');
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.