hive icon indicating copy to clipboard operation
hive copied to clipboard

ColorAdapter cast error

Open gabrc52 opened this issue 2 years ago • 5 comments

Steps to Reproduce

  1. Use Hive with List<Color>
  2. Update this value some times. It works fine
  3. Close the app and reopen it
  4. Get an exception:
type 'List<dynamic>' is not a subtype of type 'List<Color>?' in type cast

In box_impl.dart line 44.

Code sample

run twice:

await Hive.initFlutter();
Hive.registerAdapter(ColorAdapter());
await Hive.openBox<List<Color>>('colors');
final colorBox = Hive.box<List<Color>>('colors');
final colors = colorBox.get('colors', defaultValue: [
  Colors.red.shade500,
  Colors.green.shade500,
  Colors.blue.shade500,
  Colors.purple.shade500,
]); // exception here after relaunching
colorBox.put('colors', [
  Colors.orange.shade500,
  Colors.green.shade500,
  Colors.red.shade500,
  Colors.indigo.shade500,
]);

My actual code is in https://github.com/gabrc52/maingear-keyboard-lights

I tried to extract the parts that cause the exception - let me know if you need a small sample to reproduce.

Version

  • Platform: Linux (tested, other platforms untested)
  • Flutter version: 3.0.5
  • Hive version: 2.2.3

gabrc52 avatar Jul 28 '22 08:07 gabrc52

I couldn't see the class ColorAdapter in the link you sent

silverhairs avatar Jul 30 '22 11:07 silverhairs

Sorry, I forgot I'd opened this issue and changed the code to not use a ColorAdapter and do the conversion manually instead.

At the bottom (3 last functions):

https://github.com/gabrc52/maingear-keyboard-lights/blob/de350bb3483a41a355c3c500c9967b31ce526b83/lib/models/app_state.dart has a Box

https://github.com/gabrc52/maingear-keyboard-lights/blob/2cca5bc49482ccbf927d7037ba0c3e79e46d2ee8/lib/models/app_state.dart has a Box<List<Color>>

gabrc52 avatar Jul 30 '22 14:07 gabrc52

Sorry, I forgot I'd opened this issue and changed the code to not use a ColorAdapter and do the conversion manually instead.

At the bottom (3 last functions):

https://github.com/gabrc52/maingear-keyboard-lights/blob/de350bb3483a41a355c3c500c9967b31ce526b83/lib/models/app_state.dart has a Box

https://github.com/gabrc52/maingear-keyboard-lights/blob/2cca5bc49482ccbf927d7037ba0c3e79e46d2ee8/lib/models/app_state.dart has a Box<List<Color>>

Still didn't see the class ColorAdapter in both commits, but I think you might need to specify the type when registering an adapter.

Hive.registerAdapter(MyTypeAdapter());
// could be
Hive.registerAdapter<MyType>(MyTypeAdapter());

silverhairs avatar Jul 30 '22 15:07 silverhairs

Did you implement an adapter for flutter's Color class?

silverhairs avatar Jul 30 '22 16:07 silverhairs

I did so in main.dart:https://github.com/gabrc52/maingear-keyboard-lights/blob/2cca5bc49482ccbf927d7037ba0c3e79e46d2ee8/lib/main.dart

gabrc52 avatar Jul 31 '22 00:07 gabrc52