isar / hive

Lightweight and blazing fast key-value database written in pure Dart.
Apache License 2.0
4.11k stars 409 forks source link

registerAdapter does not work as shown in the example #1293

Open michelemazzei opened 5 months ago

michelemazzei commented 5 months ago

To register a serializable object in Hive the method to use is:

Hive.registerAdapter('Bee', Bee.fromJson);

But, if you use the example code:

class Person {
  String name;
  int age;
  Person(this.age, this.name); //<-- I had to add this, because name and age are not nullable

  factory Person.fromJson(Map<String, dynamic> json) {
    return Person(0, '')
      ..name = json['name'] as String
      ..age = json['age'] as int;
  }

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'age': age,
    };
  }
}
 Hive.registerAdapter('Person', Person.fromJson);

It does not compile the register Adapter method. More over if I try to force to compile (with a cast) it takes an error at runtime. Cannot use 4.0.0.dev2 , must use the 2.2.3 with @HiveType and HiveObject.

oscarshaitan commented 5 months ago

the registration is incorrect should be something like

  Hive.registerAdapter(Person Adapter());
Krzysztof-Lempicki commented 3 months ago

@oscarshaitan could you explain?

oscarshaitan commented 3 months ago

All this is with hive 2.2.3 You have this enum for example Screenshot 2024-08-02 at 10 05 34 with all the hive annotation hive will create an adapter for you inside 'distance_unit.g.dart'

Screenshot 2024-08-02 at 10 06 47 Thats the adapter you have to register Screenshot 2024-08-02 at 10 07 09

if you dont use the hive annotations you still can do it but you have to create the adapter by hand

right now if you want to play with the V4 I'll suggest you to try other solution like sembast that is json oriented the main project has been 2 years radio silent and the v4 close to 1 year. Im using currently Hive 2.2.3 but in few weeks Ill do the change. I did a bench quite tailored to my needs https://www.linkedin.com/pulse/replacing-hive-seeking-more-robust-flexible-storage-oscar-tigreros-hd5he/?trackingId=UZnb5cTgnQ%2BCx%2Bq8rI%2BiHw%3D%3D

but could help you understand what you can do