flutter:how i 在flatter/dart中创建一个Hivedao类?

t2a7ltrp  于 2021-06-24  发布在  Hive
关注(0)|答案(0)|浏览(260)

我需要将hivebd crud get、put、delete和update的所有操作分组到一个类中,但是当我尝试此操作时,会得到一个错误,因为hive.openbox()需要一个await,但构造函数不允许异步。我该如何做呢?
我的班级在下面。

  1. class HomeListRepository {
  2. var _homelistStore = await Hive.openBox<HomeList>("homelists");
  3. Future insert(String id, HomeList homelist) async {
  4. await _homelistStore.put(id,homelist.toMap());
  5. }
  6. Future update(HomeList homelist) async {
  7. await _homelistStore.put(homelist.id,homelist.toMap());
  8. }
  9. Future delete(HomeList homelist) async {
  10. await _homelistStore.delete(homelist.id);
  11. }
  12. Future<List<HomeList>> getAll() async {
  13. return _homelistStore.values;
  14. }
  15. }

编辑:我解决了这个问题,最后的代码是:

  1. class HomeListRepository {
  2. Box _homelistStore;
  3. Future<void> insert(String id,HomeList homelist) async {
  4. _homelistStore = await Hive.openBox<HomeList>("homelists");
  5. _homelistStore.put(id,homelist);
  6. }
  7. Future<void> update(HomeList homelist) async {
  8. _homelistStore = await Hive.openBox<HomeList>("homelists");
  9. await _homelistStore.put(homelist.id,homelist);
  10. }
  11. Future<void> delete(HomeList homelist) async {
  12. _homelistStore = await Hive.openBox<HomeList>("homelists");
  13. await _homelistStore.delete(homelist.id);
  14. }
  15. Future<List<HomeList>> readAll() async {
  16. _homelistStore = await Hive.openBox<HomeList>("homelists");
  17. return _homelistStore.values.toList();
  18. }
  19. }

在Hivegithub上发现page:github

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题