Populating a parent field dynamically in Dart

Issue

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

Solution

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

Answered By – Alexandre Ardhuin

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.