I'm writing a testing utility function and would like to pass a class member name and get its value. Could I use Symbol
s for this? My test code looks like this
class Foo {
String a = 'A';
String b = 'B';
static void output(Symbol symbol) {
debugPrint("The value is '$symbol'");
}
}
Foo.output(#a);
I'm trying to get a result like The value is 'A'
but I'm getting The value is 'Symbol("a")'
?
CodePudding user response:
Getting the value of something by name, where the name is a value, and at runtime, that is reflection.
You need dart:mirrors
for that, which isn't available on most platforms.
Better yet, don't do it at all. Dart has first class functions, so you can pass in a function accessing the variable instead:
class Foo {
String a = 'A';
String b = 'B';
static void output(String read(Foo value)) {
debugPrint("The value is '${read(this)}'");
}
}
void main() {
var foo = Foo();
foo.output((f) => f.a);
foo.output((f) => f.b);
}