Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Factory of object

I’ve a dataset like this:

"items": [
  {
    "title": "title1",
    "photos": [...],
    "value": {}
  },
  {
    "title": "title2",
    "photos": [...],
    "value": {
      "apple": "something",
      "pear": "lorem ipsum",
    }
  }
]

So I created two classes:

class Value {
  final String apple;
  final String pear;

  Value({
    required this.apple,
    required this.pear,
  });

  factory Value.fromJson(Map<dynamic, dynamic> json) {
    return Value(
      apple: json['apple'],
      pear: json['pear'],
    );
  }
}

class Item {
  final String title;
  final List<String> photos;
  final Value value;

  Item({
    required this.title,
    required this.photos,
    required this.value,
  });

  factory Item.fromJson(Map<dynamic, dynamic> json) {
    return Item(
      title: json['title'],
      photos: json['photos'],
      value: json['value'] // <-- ??
    );
  }
}

But when I create the data, I get Error: Expected a value of type ‘String’, but got one of type ‘_JsonMap’.
I tried to cast to Value but I get error again.
How can I solve?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As the json['value] is a JSON Object you need to parse it like below and assign it to the value.

Value.fromJson(json['value'] as Map<String, dynamic>)

so your model will look like below:

value: Value.fromJson(json['value'] as Map<String, dynamic>)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading