Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return function in Dart?

Tags:

function

dart

As Dart docs describe it, as this being purely OOP language, Functions are also object.

This can be done in JS like this :

function functionReturningFunctionJS() {
  return function functionReturnedByFunctionJS() {
      return "This is function returned by function";
  }
}

But I could not return function from function like this n dart:

Function functionReturningFunctionDart() {
  return  functionReturnedByFunctionDart(){
    return "This is function Returned By function";
  }
} 

What is the right way to do it?

like image 684
erluxman Avatar asked Jul 24 '18 03:07

erluxman


People also ask

How do you return a function in Dart?

The function's return type is string. The function returns a string value to the caller. This is achieved by the return statement. The function test() returns a string.

How do you return a function?

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number. If the value is omitted, undefined is returned instead.

How do I return two values from a function in darts?

Dart doesn't support multiple return values. or if you want the values be typed use a Tuple class like the package https://pub.dartlang.org/packages/tuple provides. See also either for a way to return a value or an error. +1 for tuple which does most closely what Go does with its built-in.

What is default return value in Dart function?

If you omit the return type then it will by default return null . All functions return a value. If no return value is specified, the statement return null ; is implicitly appended to the function body.


1 Answers

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;
}
like image 127
Dinesh Balasubramanian Avatar answered Oct 24 '22 04:10

Dinesh Balasubramanian