How to return function in Dart?
Please refer the below add function which returns the another function (or closure).
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;}
With anonymous function:
void main() { Function addTen = add(10) print(addTen(5)); //15 print(add(10)(5)); //15}Function add(int a) { return (b) => a + b;}
You can return function literals or function-containing variables, but not function declarations. To return a function declaration you can assign it to a local variable (tear-off it off) and then return it.
// OKString Function() makeFunction() { return () { return 'Hello'; };}// Also OKString Function() makeFunction2() { String myInnerFunction() { return 'Hello'; } final myFunction = myInnerFunction; // make a tear-off. return myFunction;}
And you can call the function like :
var abc = makeFunction2();print(abc());