1

I am new to both Flutter and Dart and trying to convert some android studio application to use flutter if I can. I am trying to parse some simple json to learn how all of the dart/flutter features can help me.

The class structure that I want to write to is:

class Company extends Salinas {
  final String name;
  Company({this.name}) : super();

  factory Company.fromJson(Map<String, dynamic> json) => _$CompanyFromJson(json);
  Map<String, dynamic> toJson() => _$CompanyToJson(this);
}

class Salinas {
  final int id;
  Salinas({this.id});

  factory Salinas.fromJson(Map<String, dynamic> json) => _$SalinasFromJson(json);
  Map<String, dynamic> toJson() => _$SalinasToJson(this);
}

the json string is simple

 {"id":1,"name":"Acme"}

and:

 print(company.id)is null
 print(company.name) is Acme;

when I look at the Company.g.dart file there is no reference to the extended class Salinas? is there a way to do this?

I'm clearly missing something.

1

2 Answers 2

1

You need to define extended class properties in child constructor like this:

  class Company extends Salinas {
     final String name;
     Company({id, this.name}) : super(id: id);
   }

After you will see this result:

   print(company.id) is 1
   print(company.name) is Acme;
Sign up to request clarification or add additional context in comments.

Comments

1
class Company {
  int id;
  String name;

  Company({this.id, this.name});

  Company.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    return data;
  }
}

On the basis of JSON you have provided, you should have made a Model as above. After that, you can map the whole thing quite conveniently,

Company company = Company.fromJson(response);

and then you are free to print

print(company.id);
print(company.name);

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.