10

I need to make a class which has dynamic fields which depends on what the API returns.

I am using a custom made Rest API which returns data that does not have same number of fields in all cases. Till now I was using a class with factory constructor to create objects from the response as follows:

class MyClass {
  dynamic field1;
  dynamic field2;
  dynamic field3;
  dynamic field4;

  MyClass({
    this.field1,
    this.field2,
    this.field3,
    this.field4,
  });

  factory MyClass.fromJson(dynamic json) {
    return MyClass(
      field1: json['field1'],
      field2: json['field2'],
      field3: json['field3'],
      field4: json['field4'],
    );
  }
}

The above class works well if the response is:

{
  "field1": 123,
  "field2": 432,
  "field3": 213,
  "field4": 331
}

But this does not work in all the cases as some of the responses contain less than or more than 4 fields.

It can be:

{
  "field1": 123,
  "field2": 432,
  "field3": 213
}

OR

{
  "field1": 123,
  "field2": 432,
  "field3": 213,
  "field4": 331,
  "field5": 251
}

How can I create a dynamic class which checks how many fields are there and creates itself at runtime?

3
  • 1
    Save the fields in a List or Map if the amount of fields are dynamic. Commented May 21, 2020 at 20:13
  • 1
    I know that's a way, but not looking for it. I need objects with easy property access. Im looking for something like reflection in java. Commented May 21, 2020 at 21:01
  • 3
    The purpose of classes is to have a defined interface you can use in other classes or methods. But if you classes are dynamically build on runtime with a dynamic number of methods. How are you then going to use this class in your programming? Can you give an example of how you want this to work in pseudocode? Commented May 21, 2020 at 21:08

1 Answer 1

14
+50

AFAIK, there is no way of achieving what you're asking for in Dart as of today. What you can do is:

class MyClass {
  final Map<dynamic, dynamic> data;

  MyClass(this.data);

  factory MyClass.fromJson(dynamic json) {
    assert(json is Map);
    return MyClass(json['data']);
  }
}

void main() {
  // Let's say this is your json
  final json = {
    'data': {
      'field1': 1,
      'field2': 2.2,
    },
  };

  // Create your MyClass instance
  var myClass = MyClass.fromJson(json);

  // Get the values
  var field1 = myClass.data['field1']; // prints 1
  var field2 = myClass.data['field2']; // prints 2.2
}
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.