Reputation: 335
Is there a method to call a function dynamically in Dart?
For example, in C/C++ I can use function pointers. In PHP/Javascript I can use the function name.
What I would like to achieve is placing functions in a list and iterate over the list of function to call them all on the same piece of data. How can I best accomplish this in dart?
Thanks for all the help!
Upvotes: 0
Views: 103
Reputation: 3219
You can simply use closures and function tear-offs to achieve this. Here's an example:
foo(String x) => print('Foo: $x');
bar(String x) => print('Bar: $x');
main() {
final functions = [foo, bar, (String x) => print('Closure: $x')];
for (final f in functions) {
f('data');
}
}
Which will output:
Foo: data
Bar: data
Closure: data
Upvotes: 1