質問

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);
}
役に立ちましたか?

解決

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);
}

他のヒント

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)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top