0

I was searching and didn't find anything about this topic. I want to ask if there exists any mapper or automapper for Hive box, or what is the proper way to map boxes in Hive? For example I have:

 class Company extends HiveObject {
  @HiveField(0)
  int id;

  @HiveField(1)
  String name;

  @HiveField(2)
  CompanyType type; //this is enum

  @HiveField(3)
  HiveList<Person> persons; 

  Person({this.id, this.name, this.type});
}
padaleiana
  • 955
  • 1
  • 14
  • 23
Yolanda
  • 5
  • 1
  • 6

1 Answers1

2

Generally recommending you to take a look at the official documentations, since those usually have all the answers. In this case you can take a look at the Hive documentation which also states, which dependencies are necessary to make full use of it.

Since some information / improvements are not documented too well, I will give you some examples on how I manage Hive stuff (I wrote comments in the following code-blocks):

First we declare a class which represents our custom object which should be persisted in its on box (just how you did it):

import 'package:hive/hive.dart';

/// We want to generate the class which is based on this one with its annotations which actually takes care of loading / writing this object later on (usually called just like the class itself with ".g." between name and extension (dart)
part 'connection.g.dart';

@HiveType(typeId: 0)
class Connection extends HiveObject {
  @HiveField(0)
  String name;

  ...
}

Now we will run the following command (terminal / console) every time we update our Hive classes or add new ones:

# Making use of "--delete-conflicting-outputs" to create those generated classes by deleting the old ones instead of trying to update existing ones (usually the option we want)
flutter packages pub run build_runner build --delete-conflicting-outputs

Once this is done and we have our generated classes, we need to register those in order to load them in our code later on:

/// Preferably we do this in the main function
void main() async {
  await Hive.initFlutter();

  /// Register all "Adapters" (which has just been generated via terminal)
  Hive.registerAdapter(ConnectionAdapter());

  /// Open Hive boxes which are coupled to HiveObjects
  await Hive.openBox<Connection>(
    'connections',
    /// Optional: just did that to avoid having too many dead entries
    compactionStrategy: (entries, deletedEntries) => deletedEntries > 50,
  );

  ...
}

Once all this is done, we can now securely and easily access such boxes:

/// Where ever we are in our code / widget tree, we can now just access those boxes (note how we don't have to await this, it's not async since we opened the box in the main already)
Box<Connection> box = Hive.box<Connection>('connections');

Hope this is what you were looking for.

kounex
  • 1,555
  • 4
  • 12