ZetCode

Dart function

last modified December 19, 2020

Dart function tutorial shows how to work with functions in Dart.

Dart function definition

A function is a mapping of zero or more input parameters to zero or more output parameters.

The advantages of using functions are:

Dart functions are first-class citizens. Functions can be assigned to variables, passed as arguments to functions or returned from functions. This makes the language more flexible.

The body of the function consists of statements that are executed when the function is called. We use the return keyword to return values from functions. The body is delimited with a pair of curly brackets {}. To call a function, we specify its name followed by round brackets (). A function may or may not take parameters.

Dart function simple example

The following example creates a simple function in Dart.

simple.dart
void main() {
  int x = 4;
  int y = 5;

  int z = add(x, y);

  print("Output: $z");
}

int add(int a, int b) {
  return a + b;
}

In the example, we define a function which adds two values.

void main() {

The main function is the entry point of the program.

int z = add(x, y);

We call the add function; it takes two parameters. The computed value is passed to the z variable.

int add(int a, int b) {
    return a + b;
}

The definition of the add function starts with its return value type. The parameters of the function are separated with comma; each parameter name is preceded with its data type. The statements that are executed when the function is called are placed between curly brackets. The result of the addition operation is returned to the caller with the return keyword.

print("Output: $z");

The print is a built-in Dart function, which prints the given value to the console.

$ dart simple.dart 
Output: 9

Dart arrow function

The arrow function allows us to create a simplyfied function consisting of a single expression. We can omit the curly brackets and the return keyword.

arrow_fun.dart
int add(int x, int y) => x + y;

int sub(int x, int y) => x - y;

void main() {
  print(add(3, 5));
  print(sub(5, 4));
}

In the example, we have two functions defined with the arrow syntax.

$ dart arrow_fun.dart 
8
1

Dart optional positional parameter

The square brackets [] are used to specify optional positional parameters.

optional_pos.dart
void main() {
  print(pow(2, 2));
  print(pow(2, 3));
  print(pow(3));
}

int pow(int x, [int y = 2]) {
  int r = 1;
  for (int i = 0; i < 2; i++) {
    r *= x;
  }
  return r;
}

We define a power function. The second parameter is optional; if it is not specified its default value is used to calculate the power.

$ dart optional_pos.dart 
4
4
9

Dart optional named parameters

Optional named parameters are specified insice curly {} brackets.

optional_named.dart
void main() {
  var name = "John Doe";
  var occupation = "carpenter";

  info(name, occupation: occupation);
}

void info(String name, {String occupation}) {
  print("$name is a $occupation");
}

The info function takes an optional named argument as its second argument.

info(name, occupation: occupation);

When passing the optional named parameter, we have to specify both the parameter name and value, separated with colon.

$ dart optional_named.dart 
John Doe is a carpenter

Dart anonymous function

We can create anonymous functions. Anonymous functions do not have a name.

anonymous.dart
void main() {
  var words = ['sky', 'cloud', 'forest', 'welcome'];
  words.forEach((String word) {
    print('$word has ${word.length} characters');
  });
}

We create an anonymous function which counts characters for each of the words in the list.

$ dart anonymous.dart 
sky has 3 characters
cloud has 5 characters
forest has 6 characters
welcome has 7 characters

Dart recursive function

Recursion, in mathematics and computer science, is a way of defining methods in which the method being defined is applied within its own definition. To put it differently, a recursive method calls itself to do its task. Recursion is a widely used approach to solve many programming tasks.

A typical example is the calculation of a factorial.

factorial.dart
int fact(int n) {
  if (n == 0 || n == 1) {
    return 1;
  }

  return n * fact(n - 1);
}

void main() {
  print(fact(7));
  print(fact(10));
  print(fact(15));
}

In this code example, we calculate the factorial of three numbers.

return n * fact(n - 1);

Inside the body of the fact function, we call the fact function with a modified argument. The function calls itself.

$ dart factorial.dart 
5040
3628800
1307674368000

Dart function as parameter

A Dart function can be passed to other functions as a parameter. Such a function is called a higher-order function.

funaspar.dart
int inc(int x) => ++x;

int dec(int x) => --x;

int apply(int x, Function f) {
  return f(x);
}

void main() {
  int r1 = apply(3, inc);
  int r2 = apply(2, dec);
  print(r1);
  print(r2);
}

In the example, the apply function takes the inc and dec functions as parameters.

int apply(int x, Function f) {
    return f(x);
    }

We specify that the second parameter is a function type.

int r1 = apply(3, inc);
int r2 = apply(2, dec);

We pass the inc and dec functions to the apply function as parameters.

$ dart funaspar.dart 
4
1

In this tutorial, we have covered functions in Dart.

List all Dart tutorials.