首页 > 解决方案 > Flutter Hive 无法检索 Map{}

问题描述

我正在尝试将 Map<String, int>() 存储在配置单元数据库中。我可以存储但我无法检索它提示错误的 Map()

Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, int>?' in type cast

代码:

数据控制器


Box<Map<String, int>> hiveBox = Hive.box('SaveBetBox');

  void betStorage({String? matchKey, String? statKey, int? statIndex}) {
    // Checks if the hive box has the data with following key if not adds
    hiveBox.containsKey(matchKey)
        ? null
        : hiveBox.put(
            matchKey,
            Map<String, int>(),
          );
    // Extract hive map to update or add Key values to Map with specific Key
    Map<String, int>? tm = hiveBox.get(matchKey);
    if (tm![statKey!] == null) {
      tm[statKey] = statIndex!;
      hiveBox.put(matchKey, tm);
    } else {
      tm.update(statKey, (value) => statIndex!);
    }
    Map<String, int>? dd = hiveBox.get(matchKey);
    print('This is $statKey ${dd![statKey]}');

  }

// Retrieve FN 
  void onitintHive() {
    //Storing value i.e Map() of specific key  in var
    Map<String, int>? _dd = hiveBox.get("RVB");

    // Extracting values from the map
    int? goal1 = _dd!['t1goalkey'];
    int? yc = _dd['t1yckey'];

    print('This is dd : ${_dd!['t1goalkey']}');
    print('This is T1 Goal : $goal1');
    print('This is T1 YC : $yc');
  }

main() 中的主框

  await Hive.openBox<Map<String, int>>('SaveBetBox');

标签: flutterdartflutter-hive

解决方案


我解决了这个问题。我可能错了,但似乎 Hive Box 只返回具有动态类型的地图,即Map<dynamic, dynamic>(). 发生错误是因为我试图Map<dynamic, dynamic>()适应Map<String, int>(). 更改接收器地图以Map<dynamic, dynamic>()解决问题。


推荐阅读