example:
class A {
B(){
return true;
}
C(){
return false;
}
}
var str = “B”;
how to call function B with str;
Author: Fantashit
1 thought on “how to call class method with string function name?”
The general problem requires reflection, so you can only do it using the dart:mirrors library. That library is not available on all platforms (it’s not on the web and not in Flutter).
Short of that, you need to know the possible methods ahead of time, and then you can either write a function like:
FunctiongetMember(A object, String name) {
if (name =="B") return object.B;
if (name =="C") return object.C;
throwArgumentError.value(name, "name");
}
The general problem requires reflection, so you can only do it using the
dart:mirrors
library. That library is not available on all platforms (it’s not on the web and not in Flutter).Short of that, you need to know the possible methods ahead of time, and then you can either write a function like:
or use something like
package:reflectable
to generate the function for you.