isar / hive

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

[Hive v4] Type mistmatch when get List<T> items. #1266

Open E-MRE opened 11 months ago

E-MRE commented 11 months ago
//register
Hive.registerAdapter<SampleModel>('SampleModel', (json) => SampleModel.fromJson(json));

//open box
final box = Hive.box<List<SampleModel>>(name: 'myBox');

//add items to specific key
box.put('list', const [SampleModel(id: 1, name: 'name'), SampleModel(id: 2, name: 'same')]);

//get items
final list = box.get('list');

When I try to get items from key fromJson method throws exception like "Type mismatch. Expected List but got List". Message comes from type_registry.dart class inside of the fromJson method.

If I add register adapter for list type like this

Hive.registerAdapter<List<SampleModel>>('List<SampleModel>', (json) {
      if (json is List) {
        return json.map((e) => SampleModel.fromJson(e)).toList();
      }

      debugPrint('json type: ${json.runtimeType}');
      return [];
    });

then exception message change "Type mismatch. Map<String,dynamic> but got List".

Exception throws because fromJson method doesn't support list type.

For solution we can check json is List.