Flutter Objectbox: how to store a Map attribute?

Issue

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!

Solution

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

Answered By – vaind

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.