Populating a parent field dynamically in Dart

978 Views Asked by At

I'm creating objects dynamically from Map data, populating fields for matching key names. The problem comes when fields are defined on the parent, where attempting to set a value on a parent field produces the error:

No static setter 'name' declared in class 'Skill'.

  NoSuchMethodError : method not found: 'name'

code:

class Resource {
  String name;
  String description;

  Resource.map(Map data)
  {
    ClassMirror c = reflectClass(runtimeType);
    ClassMirror thisType = c;
    while(c != null)
    {
      for (var k in c.declarations.keys) {
        print('${MirrorSystem.getName(k)} : ${data[MirrorSystem.getName(k)]}');
        if(data[MirrorSystem.getName(k)] != null)
        {
          thisType.setField(k, data[MirrorSystem.getName(k)]);        
        }
      }
      c = c.superclass;
    }
  }
}

class Skill extends Resource
{
  Skill.map(data) : super.map(data);
}
2

There are 2 best solutions below

2
On BEST ANSWER

You should use a ObjectMirror to set a field on your object. Your code tries to set a field on ClassMirror which tries to define a static variable.

class Resource {
  String name;
  String description;

  Resource.map(Map data)
  {
    ObjectMirror o = reflect(this);  // added
    ClassMirror c = reflectClass(runtimeType);
    ClassMirror thisType = c;
    while(c != null)
    {
      for (var k in c.declarations.keys) {
        print('${MirrorSystem.getName(k)} : ${data[MirrorSystem.getName(k)]}');
        if(data[MirrorSystem.getName(k)] != null)
        {
          // replace "thisType" with "o"
          o.setField(k, data[MirrorSystem.getName(k)]);
        }
      }
      c = c.superclass;
    }
  }
}

class Skill extends Resource
{
  Skill.map(data) : super.map(data);
}
0
On

Static methods/fields are not inherited in Dart.
There were already some discussions about that behavior here.
You can take a look at the answer to this question in Dart, using Mirrors, how would you call a class's static method from an instance of the class?

If the methods/fields you try to access are not static please provide more code (the classes/objects you are reflecting about)