Assign function / method to variable in Dart

Does Dart support the concept of variable functions / methods? Thus, a method call by its name is stored in a variable.

For example, in PHP this can be done not only for methods:

// With functions...
function foo()
{
    echo 'Running foo...';
}

$function = 'foo';
$function();

// With classes...
public static function factory($view)
{
    $class = 'View_' . ucfirst($view);
    return new $class();
}

I did not find it on a language tour or API. Other ways to do something like this?

Thanks in advance.

+3
source share
1 answer

To save the function name in a variable and call it later, you have to wait until reflection appears in Dart (or get creative with noSuchMethod ). However, you can store functions directly in variables, for example, in JavaScript

main() {
  var f = (String s) => print(s);
  f("hello world");
}

and even embed them, which is useful if you do a recursion:

main() {
   g(int i) {
      if(i > 0) {
         print("$i is larger than zero");
         g(i-1);
      } else {
         print("zero or negative");
      } 
   }
   g(10);
}

main() {
   var function;
   function = (String s) => print(s);
   doWork(function);
}

doWork(f(String s)) {
   f("hello world");
}
+6

All Articles