easy guide to use hive db with flutter

Youtube video or reading?

Hive is fast

Hive 1000 read and write operations

This is Hive compared to 1000 read operations as you can see, there is a huge difference compare with SQLite for example, but not too much compared to Shared preferences, but in writing we will see a different result :D

At the right we have 1000 write operations and as you can see this time we have Hive as the ultimate winner, so i really raccomand every one when he can to use it.

Don't use Hive when...

The only reason where it's not recommended to use Hive is when you have a really complex relational database, in that occasion maybe is better to use SQFlite

HiveDB is a fantastic fast and easy database to use in our applications with Flutter, without wasting other time let's start.

Installing Hive

To install hive you just have to add this dependencies to your pubspec.yaml as stated in the documentation:

Yaml
dependencies:
  hive: ^1.4.1+1
  hive_flutter: ^0.3.0+2
  path_provider: ^1.6.11

dev_dependencies:
  hive_generator: ^0.7.0+2
  build_runner: ^1.10.0

You have some troubles?

Sadly it  may happen that during the installation you may find yoursel into the problem of conflicting dartx package.

You can solve this problem by two ways; The first one is to add a dependency override just like that:

Yaml
dependency_overrides:
  dartx: ^0.3.0

If this solution does not work, and only if that doesn't work you can try to change channel from your project by going from master to stable it may solve the problem.

To do so you have to open a new terminal window and go to your project directory, from there if you type "flutter channel" you will see that you have 4 channels; So to change channel type "flutter channel stable" so it will move into the stable channel, it will take a little bit by downloading some packages.

Initializing Hive and loading first box

So now we are ready to import our dependencies and open up our first box, but before we have to do one thing, get the app directory  so then we can say to hive where we want to store our database.

Dart
import 'package:path_provider/path_provider.dart';
import 'package:hive/hive.dart';

import './models/car.dart';

void main() async {
  
  // We get the current app directory
  WidgetsFlutterBinding.ensureInitialized();
  final appDocDir = await getApplicationDocumentsDirectory();

  // We initialize Hive and we give him the current path
  Hive.init(appDocDir.path)

  var box = await Hive.openBox('people');

  box.put('123', 'Mark');
  box.put('442', 'Jacob');

  var person1 = box.get('123');
  var person2 = box.get('442');

  print(person1);

  runApp(MyApp());
}

We start to create a box variable where we will store our box, you can see boxes as tables for those who had experience with other dbs.

If it's the first time that you have called a box it will create it, if not it will load the old one.

As you can see in the code we have opened a non existent box named people using the method openBox.

Now we can put what we want inside the opened box, so using the put method we will store inside the id "123" the value "Mark" and inside "442" the value "Jacob".

We load the values stored inside the variables "person1" and "person2" and we print "person1", if you reload you will see printed inside the console the value "Mark"

Maybe using a real example? Let's create a class

Ok i think that maybe it's better to create a real example, so let's create a new class inside our project "/lib/models/car.dart"

/lib/models/car.dart

After doing so we have to create a normal class but after doing so we will have to add a special decorators:

Dart
import 'package:hive/hive.dart';

part 'car.g.dart'; // Name of the TypeAdapter that we will generate in the future

(typeId: 1)
class Car {

  (0)
  String name;

  (1)
  String model;

  (2)
  int year;

  Car(this.name, this.model, this.year);
}

The first decorator @HiveType need to be unique and for every new class that uses hive have to have one.

And for every field you have to add a HiveField decorator, 

NOTE: If you want to add a new field or delete one in the future never change the id numbers leave the as it is.

For the rest of the class is normall stuff.

Time to generate our TypeAdapter

How to generate a TypeAdapter? super simple, open a terminal window inside your project and type "flutter packages pub run build_runner build", now you will se a new file named car.g.dart inside the model folder.

Ready to Hive

Let's jump back into our main.dart file and let's change a little bit the main function:

Dart
import 'package:path_provider/path_provider.dart';
import 'package:hive/hive.dart';

import './models/car.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final appDocDir = await getApplicationDocumentsDirectory();

  Hive
    ..init(appDocDir.path)
    ..registerAdapter(CarAdapter());

  var box = await Hive.openBox('cars');

  box.put('ew32', Car('BMW','test', 2002));

  var car = box.get('ew32');

  print(car.name);

  runApp(MyApp());
}

We have imported our car model "import './models/car.dart';" changed a little bit the Hive init and added a new Hive.registerAdapter where we will have to register our adapter CarAdapter.

As before we open up a new box using "Hive.openBox('cars')" then we call the put method just as before but this time we put a Car Object.

To see our value we use box.get to get the id that we have inserted and we print the result doin car.name.

Now if you reload you will see that everything work fine and really it was so easy with HiveDB.

Thanks for reading

Thanks for reading, join our community and help us share knowledge.

flutter hive hivedb database hive database hive flutter