Hi, me again.
I'm trying to get all the records in a box, and I want to get them in a Lazy way. But it doesn't allow me to do it.
I'm try this:
(Hive.box('user') as LazyBox).values;
But the 'values' attribute cannot be used in a LazyBox and also does not return a 'Future'.
@override
Iterable get values =>
throw UnsupportedError('Only non-lazy boxes have this property.');
Is there any way to get all the elements in a 'Box' asynchronously?
Regards. :D
Do you think this is a good solution to obtain information from a box without permanently storing it in memory?
Future<List<User>> getAll() async{
final box = await Hive.openBox('user_box');
final userList = box.values;
await box.close();
return userList;
}
Would this method affect performance somewhat?
Lazy boxes are for situations where you don't have enough memory to load all data into the memory. This is why they don't support to get all values.
Do you think this is a good solution to obtain information from a box without permanently storing it in memory?
Yes it is exactly the way I would do it.
Would this method affect performance somewhat?
It is of course slower than keeping the values in memory but faster than using a lazy box.
So my DAO class would finally look like this?
class UserDao {
Future<void> insertAll(List<User> userList) async {
final box = await Hive.openBox('user_box');
box.addAll(userList);
await box.close();
}
Future<void> delete(int idUser) async {
final box = await Hive.openBox('user_box');
box.delete(idUser);
await box.close();
}
Future<void> insert(User user) async {
final box = await Hive.openBox('user_box');
box.add(user);
await box.close();
}
Future<void> update(int idUser, User user) async {
final box = await Hive.openBox('user_box');
box.put(idUser, user);
await box.close();
}
Future<List<User>> getAll() async {
final box = await Hive.openBox('user_box');
final userList = box.values;
await box.close();
return userList;
}
}
I just want to make sure I don't do bad practice with Hive :sweat_smile:
As you probably noticed, Hive is made for keeping the data in memory. Unless you need to store a crazy amount of users (where you should use a backend), I strongly suggest to keep them in memory. It will be much faster and since todays phones have 4+GB of RAM, a few kB of user objects do not matter at all.
If you still want to clear the memory every after every operation, your class is the way to go.
Thank you very much for the clarification. I will work with the first approach (keep the data in memory) and see how it works.
Regards 馃槃