简体   繁体   中英

How to encode a list of Objects to Json in Flutter?

I have a class A that contains a list of objects of another class B(Composition). Now, I want to store the object of class A to sqlite database. I learnt how to encode basic strings or integers to json but still could not find a way to encode a list of objects.

Need to save an object of concrete 'Layout'.

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

This might help you. It is not the answer to your specific case but hopefully this code will help you see how I did it in a different class.

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

Then, in the blog paragraphs class:

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

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