Reputation: 5529
I have a List<String>
of Dart function names. For example, ['func1', 'func2', 'func3']
. I want to call each function in the List
. How can I go from a String
to a Function
? The following code does not work, but conceptually it does what I want:
var func1 = Function('func1');
See how it creates a Function
from 'func1'
.
Edit: I need to deal with String
s because I read the list of functions from a file.
Upvotes: 0
Views: 217
Reputation: 8289
I don't think Dart allows that at the moment (for objects you could use dart:mirrors
, but it's currently marked as an unstable library).
An alternative is to use a Map to associate the strings with the functions, as in:
void foo() {
print('foo');
}
void bar() {
print('bar');
}
void main() {
var functions = {
'foo': foo,
'bar': bar
};
// calling foo()
functions['foo']();
// or
var b = functions['bar'];
b();
}
Upvotes: 1