#FreePalestine 🇵🇸

Muhammed Mukhthar CM

Storing Custom Class Objects in Hive

Mar 16, 2021 3 min read
Storing Custom Class Objects in Hive

⚠️ This post is intended for people who have just Started using Hive Db.

Hive is a NoSql Database. According to Documentation,

Hive is a lightweight and blazing fast key-value database written in pure Dart`.

It’s not just words, It is pretty fast.

When we first setup, Hive is only able to store Dart primitive datatypes. It means, we can only store String,int,bool etc. in Hive Database.

Eventhough this is the case initially, we can still store our beloved 😉 Dart objects. For this, we have to create TypeAdaptors for our needed Dart Objects. Fear not, it is too easy to create.

Adding Packages

First of all, let’s add the necessory packages requird for Hive to Work. We have to add hive package ofcource. If you’re working on a Flutter project, It’ll be handy to add hive_flutter as well.

dependencies:
  flutter:
    sdk: flutter
  hive: ^2.0.0
  hive_flutter: ^1.0.0

But we’re not yet completed with our packages. For Creating the above told TypeAdaptors, we have to add 2 more packages to our pubspec.yaml file. we have to add build_runner and hive_generator in our dev_dependencies list.

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^1.12.1
  hive_generator: ^1.0.0

These two packages are used to Generating TypeAdaptors.

Creating Model Class

Once we are ready with packages, it’s the time to create Model Classes for our object. For this, apart from usual, we’ll have to do some annotations.

import 'package:hive/hive.dart';

part 'note_model.g.dart';

@HiveType(typeId: 0)
class NoteModel {
  @HiveField(0)
  String title;

  @HiveField(1)
  String content;

  @HiveField(2)
  DateTime createdTime;
}

If you’ve noticed, you should’ve seen that there are some unfamiliar things like @HiveType and HiveField in the above class.

  • @HiveType is used to mark the current for generation of TypeAdaptor. We should provide a unique typeId: for each HiveTypes.
  • @HiveField also must have unique numbers with them.
  • Those numbers are used to identify the fields in Hive binary format, as per documentation. They also says that we should not change those numbers after our app in in use.
  • We should also add the part 'note_model.g.dart'; line replacing note_model with the actual filename of your class. Otherwise, the Adaptor will not be generated.
    • At first, this line will show error. Don’t worry, this will go after the next step.

Generating TypeAdaptor

After the above steps are completed, it’s time for generating the TypeAdaptor. for this run the below command in your terminal.

flutter packages pub run build_runner build

After this, the above mentioned errors must’ve gone. and if you look, you’ll notice, a new file named note_model.g.dart if the model class file name was note_model.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'note_model.dart';

// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************

class NoteModelAdapter extends TypeAdapter<NoteModel> {
  @override
  final int typeId = 0;

  @override
  NoteModel read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return NoteModel()
      ..title = fields[0] as String
      ..content = fields[1] as String
      ..createdTime = fields[2] as DateTime;
  }

  @override
  void write(BinaryWriter writer, NoteModel obj) {
    writer
      ..writeByte(3)
      ..writeByte(0)
      ..write(obj.title)
      ..writeByte(1)
      ..write(obj.content)
      ..writeByte(2)
      ..write(obj.createdTime);
  }

  @override
  int get hashCode => typeId.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is NoteModelAdapter &&
          runtimeType == other.runtimeType &&
          typeId == other.typeId;
}

Registering TypeAdaptor

Now we are into the last part. Inorder to these TypeAdaptors to work, we have to register them. It is simple as adding Hive.registerAdapter(NoteModelAdapter()); to your main function, just right below the Initialization of Hive.

Now you can use these objects as you do with any other dart primitives with Hive.

aka. Hive.box('notes').add(NoteModel()); should add the noteModel to a Hive box named notes.

Finishing up

I think this was useful to you. If you have any doubts or found a mistake in this, please let me know in my Twitter or drop a mail at [email protected].

Finally, if you found this helpful, please share this within your reach so that more people can benefit from this. And Follow me on Twitter for getting more posts like these 😉.


Support Me