Flutter Objectbox:如何存储 Map 属性?
Flutter Objectbox: how to store a Map attribute?
我有一个带有 Map 属性的 class,但它似乎没有存储此属性。所有其他属性都很好地存储:
@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
仍然是空的。
谢谢!
对于不受支持的类型,您需要添加一个“转换器”,如 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)));
}
}
}
我有一个带有 Map 属性的 class,但它似乎没有存储此属性。所有其他属性都很好地存储:
@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
仍然是空的。
谢谢!
对于不受支持的类型,您需要添加一个“转换器”,如 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)));
}
}
}