Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a parent field dynamically in Dart

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);
}
like image 566
Todd Chambery Avatar asked Jan 05 '14 13:01

Todd Chambery


2 Answers

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);
}
like image 159
Alexandre Ardhuin Avatar answered Nov 12 '22 22:11

Alexandre Ardhuin


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)

like image 3
Günter Zöchbauer Avatar answered Nov 12 '22 22:11

Günter Zöchbauer