2

I am wondering if there is anyway to call a function by its name in dart as in javascript.

I would like to do something as such:

foo["bar"]();
Community
  • 1
  • 1
Erik
  • 128
  • 2
  • 14

1 Answers1

7

I don't want readers to think what the questioner wants isn't possible in Dart, so I'm adding an answer.

You need to use Mirrors to call a method if you have its name available as a string. Here is an example:

import 'dart:mirrors';

class Foo {
  bar() => "bar";
}

void main() {
  var foo = new Foo();

  var mirror = reflect(foo);
  print(mirror.invoke(#bar, []).reflectee); // Prints 'bar'.
}
Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51