Home > Software engineering >  Nested JSON values are shown in the debugger but are returned as null from factory method
Nested JSON values are shown in the debugger but are returned as null from factory method

Time:10-14

I have a JSON object on Firebase that contains the "gameInfo" map shown below. I'm trying to parse that object in order to retrieve the values of the text and title fields and despite the values being logged in the console successfully and their values being present in the debugger, when the GameInfo instance is returned from the factory fromJson() method, all fields are null. What am I missing here?

schema

Here's where I'm calling the GameInfo.fromJson():

final GameInfo info =
        GameInfo.fromJson(json['gameInfo'] as Map<String, dynamic>);

GameInfo.dart:

class GameInfo {
  String? title1;
  String? title2;
  String? title3;
  String? desc1;
  String? desc2;
  String? desc3;

  GameInfo(
      {required String? title1,
      required String? title2,
      required String? title3,
      required String? desc1,
      required String? desc2,
      required String? desc3});

  factory GameInfo.fromJson(Map<String, dynamic> json) {
    return GameInfo(
      title1: json['title1'] == null || json['title1'].isEmpty
          ? null
          : json['title1']['en'] as String,
      title2: json['title2'] == null || json['title2'].isEmpty
          ? null
          : json['title2']['en'] as String,
      title3: json['title3'] == null || json['title3'].isEmpty
          ? null
          : json['title3']['en'] as String,
      desc1: json['text1'] == null || json['text1'].isEmpty
          ? null
          : json['text1']['en'] as String,
      desc2: json['text2'] == null || json['text2'].isEmpty
          ? null
          : json['text2']['en'],
      desc3: json['text3'] == null || json['text3'].isEmpty
          ? null
          : json['text3']['en'] as String,
    );
  }
}

Finally, here's the debugger view:

debugger view

CodePudding user response:

I found your problem :) just swap code, look below;

change

 GameInfo(
      {required String? title1,
      required String? title2,
      required String? title3,
      required String? desc1,
      required String? desc2,
      required String? desc3});
...

to

 GameInfo(
      {this.title1,
      this.title2,
      this.title3,
      this.desc1,
      this.desc2,
      this.desc3});
...

--edit

The above code is compile by dart SDK into the below code in the background. So, above code snippet is a shortened version

GameInfo(
    {required String title1,
      required String title2,
      required String title3,
      required String desc1,
      required String desc2,
      required String desc3}){
  this.title1 = title1;
  this.title2 = title2;
  this.title3 = title3;
  this.desc1 = desc1;
  this.desc2 = desc2;
  this.desc3 = desc3;
}
  • Related