dart 类型“List< dynamic>”不是< Bookingday>使用Flutter Hive进行类型转换的类型“List?”的子类型

pkbketx9  于 2023-07-31  发布在  Flutter
关注(0)|答案(2)|浏览(117)

以下问题:
我在我的项目中有Hive,在那里我保存对象列表。当我在使用应用程序时存储一些东西,并希望从Hive获取数据(仍然是相同的会话),然后一切都很好,我得到了我以前存储在Hive中的数据。当我查看我的文档文件夹时,还有一个.Hive文件,其中存储了我的数据。但是在我关闭应用程序后,当我想从Hive获取数据时,它告诉我:

" type 'Unhandled exception:
type 'List<dynamic>' is not a subtype of type 'List<Bookingday>?' in type cast
#0      BoxImpl.get (package:hive/src/box/box_impl.dart:44:26)
#1      BookingDAO.Eval ()
#2      BookingDAO.getStoredWeek (package:workplace/utils/booking_dao.dart:23:36)
#3      _ReservationsState.initState (package:workplace/pages/reservations.dart:44:30)

字符串
我不能理解这种行为。为什么它工作得很好,当我在同一个会话中存储和获取数据时,但在重新启动应用程序后,它说List是动态类型?这和我如何打开和关闭Hive有关吗?
我的方法:

Box<List<Bookingday>> boxList = Hive.box<List<Bookingday>>(bookingDayBoxName);

    List<Bookingday> getStoredWeek(DateTime firstJan, DateTime date) {
        String key = getCalenderWeek(firstJan, date);
        try {
          List<Bookingday>? bookList = boxList.get(key);
          if (bookList != null) {
            bookingdays = bookList;
            return bookList;
          } else {
            return List.generate(
                getWeek(dateNow).length,
                (index) => Bookingday(
                    day: dateNow,
                    parkingSlotReserved: false,
                    capacityCounter: 0,
                    maxCapacity: 4));
          }
        } catch (e) {
            if (e is TypeError) {}
        }
        return bookingdays;
     }

busg9geu

busg9geu1#

Box<List> box = Hive.box<List>(bookingDayBoxName);
var list = box.get(key, defaultValue: [])?.cast<Bookingday>();

字符串
因为Dart的局限性

jq6vz3qz

jq6vz3qz2#

试投

Box<List<Bookingday>> boxList = Hive.box<List<Bookingday>>(bookingDayBoxName);

    List<Bookingday> getStoredWeek(DateTime firstJan, DateTime date) {
        String key = getCalenderWeek(firstJan, date);
        try {
          List<Bookingday>? bookList = boxList.get(key);
          if (bookList != null) {
            bookingdays = bookList!;
            return bookList;
          } else {
            return List.generate(
                getWeek(dateNow).length,
                (index) => Bookingday(
                    day: dateNow,
                    parkingSlotReserved: false,
                    capacityCounter: 0,
                    maxCapacity: 4)).cast<Bookingday>();
          }
        } catch (e) {
            if (e is TypeError) {}
        }
        return bookingdays;
     }

字符串

相关问题