[英]Flutter Objectbox: how to store a Map attribute?
我有一個 class 和 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
仍然是空的。
謝謝!
對於不受支持的類型,您需要添加一個“轉換器”,如文檔(自定義類型)中所述。 您可以根據您的代碼調整文檔,例如使用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)));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.