0

我有一个带有 Map 属性的类,但它似乎没有存储这个属性。所有其他属性都保存得很好:

@JsonSerializable()
@Entity()
class PossessionStats {
  @JsonKey(defaultValue: 0)
  int id;
  String cardUuid;
  int total;
  Map<String, int>? totalByVersion;

  CardPossessionStats({
    this.id = 0,
    required this.cardUuid,
    this.total = 0,
    this.totalByVersion,
  });
}

当我保存一个时:

stats = PossessionStats(cardUuid: card.uuid);
if (stats.totalByVersion == null) {
  stats.totalByVersion = Map();
}
stats.totalByVersion!
    .update(version, (value) => quantity, ifAbsent: () => quantity);
stats.total = stats.totalByVersion!.values
    .fold(0, (previousValue, element) => previousValue + element);
box.put(stats);

当我得到结果时(刷新后),我可以看到total是正确的,但totalByVersion仍然是空的。

谢谢!

4

1 回答 1

4

对于不受支持的类型,您需要添加一个“转换器”,如docs (Custom types)所述。您可以使文档适应您的代码,例如json用作存储格式:

@JsonSerializable()
@Entity()
class PossessionStats {
  @JsonKey(defaultValue: 0)
  int id;
  String cardUuid;
  int total;
  Map<String, int>? totalByVersion;

  String? get dbTotalByVersion =>
      totalByVersion == null ? null : json.encode(totalByVersion);

  set dbTotalByVersion(String? value) {
    if (value == null) {
      totalByVersion = null;
    } else {
      totalByVersion = Map.from(
          json.decode(value).map((k, v) => MapEntry(k as String, v as int)));
    }
  }
}
于 2021-08-23T11:03:16.197 回答