如何在Dart中返回函数?

erl*_*man 5 function dart

至于飞镖文档 describe它,因为这是纯粹的OOP语言Functions也是object

可以在JS这样完成:

function functionReturningFunctionJS() {
  return function functionReturnedByFunctionJS() {
      return "This is function returned by function";
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我不能从像n dart这样的函数返回函数:

Function functionReturningFunctionDart() {
  return  functionReturnedByFunctionDart(){
    return "This is function Returned By function";
  }
} 
Run Code Online (Sandbox Code Playgroud)

正确的做法是什么?

Din*_*ian 12

请参考下面的 add 函数,它返回另一个函数(或闭包)。

void main() {
  Function addTen = add(10);
  print(addTen(5)); //15
  print(add(10)(5)); //15
}

Function add(int a) {
    int innerFunction(b) {
        return a + b;
    }
    return innerFunction;
}
Run Code Online (Sandbox Code Playgroud)

使用匿名函数:

void main() {
  Function addTen = add(10)
  print(addTen(5)); //15
  print(add(10)(5)); //15
}

Function add(int a) {
    return (b) => a + b;
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*ams 6

您可以返回函数文字或包含函数的变量,但不能返回函数声明。要返回函数声明,您可以将其分配给局部变量(将其撕掉)然后返回。

// OK
String Function() makeFunction() {
  return () {
    return 'Hello';
  };
}

// Also OK
String Function() makeFunction2() {
  String myInnerFunction() {
    return 'Hello';
  }
  final myFunction = myInnerFunction; // make a tear-off.
  return myFunction;
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样调用函数:

var abc = makeFunction2();
print(abc());
Run Code Online (Sandbox Code Playgroud)