I want to build a method to dynamically save attributes on a specific object

given the attribute name and the value to save I call the "save()" function to update the global targetObj

var targetObj = targetClass();

save(String attribute, String value){
  targetObj.attribute = value;

  print(targetObj.attribute);
}

But I'm getting the following error:

Class 'targetClass' has no instance setter 'attribute='.
Receiver: Instance of 'targetClass'
Tried calling: attribute="Foo"

The only thing that I can think of is that "attribute" due to being type String results in an error.

That lead me to think if there is a way to read a String as code, something like eval for php.


Solution 1: Randal Schwartz

Dart (and thus flutter) does not have a way to compile and execute code at runtime (other than dart:mirrors, which is deprecated). You can build additional code that derives from other code using the various builder mechanisms, although it can be rather complicated to implement (and use!).


Solution 2: dm_tr

As @Randal mentioned, you cannot create class..method at runtime. Still, you can try something like this.

A certain class

class Foo {
  dynamic bar1;
  dynamic bar2;
  // ...
}

Your save method

save(Foo fooObject, String attribute, dynamic value) {
  if ("bar1" == attribute) fooObject.bar1 = value;
  else if ("bar2" == attribute) fooObject.bar2 == value;
  // ...
}