【问题标题】:How to encode a list of Objects to Json in Flutter?如何在 Flutter 中将对象列表编码为 Json?
【发布时间】:2021-04-21 13:22:28
【问题描述】:

我有一个 A 类,其中包含另一个 B 类(组合)的对象列表。现在,我想将 A 类的对象存储到 sqlite 数据库中。我学会了如何将基本字符串或整数编码为 json,但仍然找不到编码对象列表的方法。

需要保存一个具体的“布局”对象。

class MallardDuck extends Duck {
  var image = "https://image.shutterstock.com/image-vector/cartoon-duck-swimming-600w-366901346.jpg";

  Widget d_widget;
  List<Widget> previous_states = [];
  List<Widget> redo_states = [];
}
abstract class Layout extends Duck{

  List<Duck> listOfDucks = [];
  bool default_layout;
}

【问题讨论】:

  • 由于您使用的是sqflite 数据库,因此更简洁的方法是为每个类使用单独的表。然后通过迁移外键进行关联
  • 你能推荐除 sqlite 之外的任何其他方法吗?唯一的目的是保存应用程序的状态,当我重新启动时,它会从我离开的地方开始。
  • 没有将“对象”编码为 JSON 的通用方法。每个类的 to/fromJSON 必须是手工制作的(有时需要机械辅助)。

标签: json sqlite flutter dart


【解决方案1】:

这可能会对您有所帮助。 这不是针对您的具体案例的答案,但希望这段代码可以帮助您了解我在不同的班级中是如何做到的。

class BlogData {
  final String title;

  final String associatedBusinessId;

  final String category;

  final List<BlogParagraph> blogParagraphs;

  BlogData(
      {this.title,
      this.associatedBusinessId,
      this.category,
      this.blogParagraphs});

  Map<String, dynamic> toJson() {
    return {
      'title': this.title,
      'associatedBusinessId': this.associatedBusinessId,
      'category': this.category,
      'blogParagraphs':
          blogParagraphs.map((paragraph) => paragraph.toJson()).toList()
    };
  }
}

然后,在博客段落类中:

class BlogParagraph {
  final int paragraphId;

  final String content;

  final Set<int> imageRefs;

  BlogParagraph({this.paragraphId, this.content, this.imageRefs});

  Map<String, dynamic> toJson() {
    return {
      'id': this.paragraphId,
      'content': this.content,
      'imageRefs': imageRefs.isEmpty ? [] : imageRefs.toList(),
    };
  }
}

【讨论】:

    猜你喜欢
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2021-05-13
    • 2012-06-10
    • 2021-04-20
    • 2020-06-30
    • 2023-04-02
    相关资源
    最近更新 更多