Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Hivebox value is returning List<dynamic> instead of saved List<Object>

I save a List to an index in a Hive Box.

class Person { 
 String name;
 Person(this.name);
}

List<Person> friends = [];
friends.add(Person('Jerry'));

var accountBox = Hive.openBox('account');
accountBox.put('friends',friends);

//Testing as soon as saved to make sure it's storing correctly.
List<Person> friends = accountBox.get('friends');
assert(friends.length == 1);

so all this works as intended. For some crazy reason when I hot restart the app and try to get the list of friends from Hive, it no longer returns a List<Person>. It returns a List<dynamic>

var accountBox = Hive.openBox('account');
List<Person> friends = accountBox.get('friends');

///ERROR
E/flutter (31497): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled
Exception: type 'List<dynamic>' is not a subtype of type 'List<Person>'
E/flutter (31497): <asynchronous suspension>
etc...

What could be causing this? It's so unusual.

like image 580
ZeroNine Avatar asked Oct 27 '25 07:10

ZeroNine


2 Answers

This solved the problem for me

var fooBox = await Hive.openBox<List>("Foo");

var foosList = fooBox.get("foos", defaultValue: []).cast<Foo>();
print(foosList);

This solution from github issue

like image 83
mkju Avatar answered Oct 28 '25 23:10

mkju


There's is an easy way of transforming back your information.

List<T> myList = box.get('key', defaultValue: <T>[]).cast<T>();

As you can see in this example when you get your data you just need to tell the Type for you data to be correctly assigned.

like image 44
Lutfi Garzon Avatar answered Oct 28 '25 22:10

Lutfi Garzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!