Steps to Reproduce
I am trying to store a complete list of objects in a box. I want to try and do that instead of iterating through all elements out of the box with box.values.toList().cast<MyObject>();. I would like to see if it would be better performance-wise at least.
So if I initially do the following:
everything works and I get the expected result.
Now if I comment out step number 2 and hot reload, i.e. if I do the following:
I get the following error:
E/flutter ( 7584): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<Foo>' in type cast
E/flutter ( 7584): #0 BoxImpl.get (package:hive/src/box/box_impl.dart:34:26)
E/flutter ( 7584): #1 initializeHive (package:[omitted]/main.dart:45:25)
E/flutter ( 7584): <asynchronous suspension>
E/flutter ( 7584): #2 main (package:[omitted]/main.dart:22:9)
E/flutter ( 7584): <asynchronous suspension>
E/flutter ( 7584): #3 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:229:25)
E/flutter ( 7584): #4 _rootRun (dart:async/zone.dart:1124:13)
E/flutter ( 7584): #5 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 7584): #6 _runZoned (dart:async/zone.dart:1516:10)
E/flutter ( 7584): #7 runZoned (dart:async/zone.dart:1500:12)
E/flutter ( 7584): #8 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:221:5)
E/flutter ( 7584): #9 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:19)
E/flutter ( 7584): #10 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
Code sample
Here is the Foo object:
import 'package:hive/hive.dart';
part 'foo.g.dart';
@HiveType()
class Foo extends HiveObject {
@HiveField(0) final String id;
Foo(this.id);
@override
String toString() {
return 'Foo{id: $id}';
}
}
The code for the storing:
var fooBox = await Hive.openBox<List<Foo>>("Foo");
var foos = [Foo("1"), Foo("2")];
fooBox.put("foos", foos);
var foosList = fooBox.get("foos", defaultValue: []);
print(foosList);
and the code that throws the error
var fooBox = await Hive.openBox<List<Foo>>("Foo");
var foosList = fooBox.get("foos", defaultValue: []);
print(foosList);
Version
This is a limitation of Dart. Use the following:
var fooBox = await Hive.openBox<List<Foo>>("Foo");
var foosList = fooBox.get("foos", defaultValue: []).cast<Foo>();
print(foosList);
I still get the same errors if I use the code you provided.
Sorry:
var fooBox = await Hive.openBox<List>("Foo");
var foosList = fooBox.get("foos", defaultValue: []).cast<Foo>();
print(foosList);
That did the trick! Thanks for the info... I wouldn't have guessed that that was the case
I spent half a day trying to figure this bug out, solved thanks to this issue. @leisim Do the docs say anything about this?
@MaskyS
Do the docs say anything about this?
Yes, at the very bottom of this page. Maybe I should mention it at other places too...
Most helpful comment
Sorry: