0

I'm trying to parse a JSON file from the web, and while I can parse most of the fields, I can't seem to pass some of them inside the constructor. Some come out fine, the others come out as null. This is my constructor

Event({
  this.title,
  this.comment,
});

And this is my factory constructor which decodes the JSON of each event:

factory Event.fromJson(Map<String, dynamic> json) {
  String s = json['EVENT_COMMENT'];
  print('event comment: $s'); //this prints well, gives me the exact comment of the event found in the JSON file

  return Event(
    title: json['EVENT_TITLE'],  //fine, gives me the exact title of the event in the JSON file
    comment: s, // when I try to print the whole list of events, with toString() method overridden, this comes out as null
  );
}

This is my toString() method overridden in this same class (when I call this method on this class's object, it returns title fine, whereas comment is null):

@override
String toString() {
  return '$title, $comment';
}

I have never had this weird thing happen to me, I have almost always been able to successfully parse JSON in Dart. Am I missing something here?

(Spared most of the details so that it is straightforward)

Edit: This is one of the JSON objects I'm parsing (all of them have the same fields):

{
...
  "EVENT_COMMENT": "This is a cool event.",
  "EVENT_TITLE": "Some event title here.",
...
},

Edit 2: this one also returns null when called, for some reason:

String getComment() => comment;

bqubique
  • 678
  • 6
  • 17
  • 1
    I think your codes are good. The problem is in something else you didn't provide. – Shady Boshra Mar 02 '21 at 08:03
  • 1
    Could you provide a JSON sample you are trying to parse. – Guillaume Roux Mar 02 '21 at 08:10
  • @ShadyBoshra yeah, the weird thing is when I'm printing the s string before the constructor, it's fine, it prints out what I expect, but when I'm printing it with toString() or with `String getComment() => comment;` method, I get null. Pretty strange. – bqubique Mar 02 '21 at 08:26

0 Answers0