A way to read a String as dart code inside flutter?
Solution 1
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;
// ...
}
Solution 2
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!).
Comments
-
leshugo33 over 1 year
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.
-
leshugo33 over 3 yearsAny insight is appreciated :)
-
-
leshugo33 over 3 yearsThank you, unfortunately I would have to do 40+ cases using this approach but It seems like there is no other way
-
dm_tr over 3 yearsIndeed! No way to build class name, variable name or method name dynamically