简体   繁体   中英

Flutter Objectbox: how to store a Map attribute?

I have a class with a Map attribute, but it seems it doesn't store this attribute. All other attributes are well stored:

@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,
  });
}

When I save one:

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);

When I get the results (after a refresh), I can see total is correct but totalByVersion is still empty.

Thanks!

For an unsupported type, you'll need to add a "converter", as described by the docs (Custom types) . You can adapt the docs to your code, for example using json as the storage format:

@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)));
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM