簡體   English   中英

Flutter Objectbox:如何存儲一個 Map 屬性?

[英]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)));
    }
  }
}

Flutter如何轉換List<object> 用於使用 ObjectBox<div id="text_translate"><p> 我有一個 model 這樣的代碼</p><pre>class Folder { int id; String title; Color? color; List<Note> notes; final user = ToOne<User>(); String? get dbNotes => json.encode(notes); set dbNotes(String? value) { notes = json.decode(value;). } //... }</pre><p> 我有這個錯誤</p><pre>Cannot use the default constructor of 'Folder': don't know how to initialize param notes - no such property.</pre><p> 如何將我的 List<Object> 轉換為存儲在 ObjectBox 中?</p></div></object>

[英]Flutter how to convert List<Object> for using ObjectBox

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM