Home > database >  Factory of object
Factory of object

Time:03-10

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?

CodePudding user response:

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>)
  • Related