【问题标题】:Flutter Objectbox: how to store a Map attribute?Flutter Objectbox:如何存储 Map 属性?
【发布时间】:2021-08-23 08:27:25
【问题描述】:

我有一个带有 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 仍然是空的。

谢谢!

【问题讨论】:

    标签: flutter objectbox flutter-objectbox


    【解决方案1】:

    对于不受支持的类型,您需要添加一个“转换器”,如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)));
        }
      }
    }
    

    【讨论】:

    • 完美,谢谢!我第一次尝试时它不起作用,但你的例子很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多