Reputation: 2678
I would like to select an object in a class by its name stored in a variable. Is this feasible? So basically a syntax for the placeholder -magic_syntax-
or any other method how this can be achieved.
const String kListNames = {'list1', 'list2'};
class MyClass {
List<int> list1 = [0, 1, 2];
List<bool> list2 = [true, false];
}
main() {
List<dynamic> myList;
MyClass myClass;
for (var listName in kListNames) {
myList = myClass.-magic_syntax-(listName);
}
}
Upvotes: 0
Views: 247
Reputation: 807
Dart is a Compile time language. It's not possible to interact with variables through their variable names in the way you're suggesting.
why not store your data in a Map?
Map<String, List> myData = {
'list1': [0, 1, 2],
'list2': [true, false],
}:
for(final listName in myData.keys) {
...
}
now you can loop over the data keys myData.keys
, the values myData.values
or both myData.entries
Upvotes: 1