Flutter Hive - Unhandled exception: type 'List<dynamic>' is not a subtype of type 'List<SourceStations>' in type cast

Viewed 3673

I am using this package https://pub.dev/packages/hive

I want to save and retrieve a list of custom objects in the hive.

I have tried to below approach

await Hive.openBox<List<SourceStations>>(stationBox); //Open box
Box<List<SourceStations>> sourceStationsBox = Hive.box(stationBox); 
sourceStationsBox.put(stationBox, listSourceStation); //Saving list of custom object as listSourceStation
//Should probably give lenght of list of custom object
logger.d('station box list length is ${sourceStationsBox.get(stationBox).length}'); 

But I am getting below error

E/flutter (24061): [ERROR:flutter/shell/common/shell.cc(199)] Dart Error: Unhandled exception: E/flutter (24061): type 'List' is not a subtype of type 'List' in type cast E/flutter (24061): #0 BoxImpl.get (package:hive/src/box/box_impl.dart:43:26) E/flutter (24061): #1
_SourceToDestinationPageState.openStationBox

I have tried checking this solution but not getting enough idea how to fix this.

Following are the hive version I am using

  • hive: ^1.3.0
  • hive_flutter: ^0.3.0+1
  • hive_generator: ^0.7.0
2 Answers

"Generic type parameters like Box<List> are unsupported due to Dart limitations." This is mentioned in the author documentation: https://docs.hivedb.dev/#/basics/boxes at the bottom of the page.

If you are not using a ValueListenableBuilder, you can do it like this:

await Hive.openBox<List<SourceStations>>(stationBox); //Open box
Box<List<SourceStations>> sourceStationsBox = Hive.box(stationBox); 
sourceStationsBox.put(key, listSourceStation); // key is a string
logger.d('station box list length is ${sourceStationsBox.get(key).length}'); 
Related