0

Following is my json output

{
    "success": true,
    "data": {
        "id": 1,
        "username": "MV",
        "name": "Saraa",
        "userSponsorData": {
            "initial": "GT",
            "name": "Green Trust",
            "email": "[email protected]",
            "username": "trust",
            "phone": "1234567890"
        }
    }
}

Following is part of my model dart file

class UserDetailModel {
  bool success;
  Data data;

  UserDetailModel({this.success, this.data});

  UserDetailModel.fromJson(Map<String, dynamic> json) {
    success = json['success'];
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
  }
}

By parsing I am able to get the values under jsonObject "data", the values are able to be printed

class Data {
  String name;
  String email;
  String uname;
  String phone;
  SponsorData sData;

  Data({this.name, this.email, this.uname, this.phone, this.sData});

  Data.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    email = json['email'];
    uname = json['username'];
    phone = json['phone'];
    sData = json['userSponsorData'] != null
        ? new SponsorData.fromJson(json['userSponsorData'])
        : null;
  }
}

but not able to retrieve from jsonObject "userSponsorData" - while i try to print the values,

NoSuchMethodError: The getter 'initial' was called on null. - how to fix this

1 Answer 1

1
void main() {
    var value = {
      "success": true,
      "data": {
        "id": 1,
        "username": "MV",
        "name": "Saraa",
        "userSponsorData": {
          "initial": "GT",
          "name": "Green Trust",
          "email": "[email protected]",
          "username": "trust",
          "phone": "1234567890"
        }
      }
    };
    new Data.fromJson(value['data']);
}

class Data {
  String name;
  String email;
  String uname;
  String phone;
  SponsorData sData;

  Data({this.name, this.email, this.uname, this.phone, this.sData});

  Data.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    email = json['email'];
    uname = json['username'];
    phone = json['phone'];
    sData = json['userSponsorData'] != null
        ? new SponsorData.fromJson(json['userSponsorData'])
        : null;
  }
}

class SponsorData {
  String sdata;
  SponsorData({this.sdata});
  SponsorData.fromJson(Map<String, dynamic> json) {
    var initial = json['initial'];
    var name = json['name'];
    var email = json['email'];
    var username = json['username'];
    var phone = json['phone'];
    print("$initial , $name , $email");
  }
}

sucess result

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.