TExcelTAD
Home › Flutter › Dart Functions

Dart Functions

A function packages a piece of logic under a name so you can reuse it. In Dart, functions are also objects: you can store them in variables and pass them to other functions. Flutter relies on that constantly — every onPressed: () { ... } is a function passed as a value.

Defining and calling functions

A function declaration has a return type, a name, a parameter list and a body.

dart · try it yourself
int add(int a, int b) {
  return a + b;
}

void greet(String name) {
  print('Hello, $name!');
}

void main() {
  print(add(2, 3));
  greet('Khoa');
}
5
Hello, Khoa!

If a function returns nothing, its return type is void.

Arrow functions

When the body is a single expression, use the arrow syntax => expression. It's shorthand for { return expression; }.

dart · try it yourself
int square(int x) => x * x;
bool isAdult(int age) => age >= 18;
String shout(String s) => '${s.toUpperCase()}!';

void main() {
  print(square(9));
  print(isAdult(16));
  print(shout('hey'));
}
81
false
HEY!

Optional and named parameters

Dart has three kinds of parameters:

Kind Syntax Call
Required positional f(int a) f(1)
Optional positional f([int a = 0]) f() or f(1)
Named f({int a = 0}) f() or f(a: 1)
Required named f({required int a}) f(a: 1)

Named parameters make calls self-documenting, which is why every Flutter widget constructor uses them: Text('Hi', textAlign: TextAlign.center).

dart · try it yourself
String formatPrice(double amount, [String currency = 'USD']) =>
    '${amount.toStringAsFixed(2)} $currency';

void createUser({required String name, int age = 18, String? email}) {
  print('name=$name age=$age email=${email ?? 'none'}');
}

void main() {
  print(formatPrice(9.5));
  print(formatPrice(120000, 'VND'));

  createUser(name: 'Lan');
  createUser(name: 'Tuan', email: 'tuan@example.com', age: 30);
}
9.50 USD
120000.00 VND
name=Lan age=18 email=none
name=Tuan age=30 email=tuan@example.com

Named arguments can be passed in any order. A named parameter must either have a default value, be nullable (String?), or be marked required.

Functions as values

Functions can be assigned to variables, passed as arguments and returned from other functions. A function that takes or returns a function is called a higher-order function.

dart · try it yourself
int applyTwice(int Function(int) f, int value) => f(f(value));

void main() {
  int Function(int) triple = (n) => n * 3;

  print(applyTwice(triple, 2));
  print(applyTwice((n) => n + 10, 1));

  var numbers = [1, 2, 3, 4];
  var doubled = numbers.map((n) => n * 2).toList();
  print(doubled);
}
18
21
[2, 4, 6, 8]

(n) => n * 3 is an anonymous function (also called a lambda or closure). The type int Function(int) describes "a function taking an int and returning an int". In Flutter, VoidCallback is simply a name for void Function().

Closures

A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished.

dart · try it yourself
int Function() makeCounter() {
  var count = 0;
  return () {
    count++;
    return count;
  };
}

void main() {
  var counterA = makeCounter();
  var counterB = makeCounter();

  print(counterA());
  print(counterA());
  print(counterA());
  print(counterB());
}
1
2
3
1

Each call to makeCounter creates a new count variable, and each returned closure keeps its own copy.

Returning several values

Use a record to return more than one value, and destructure it at the call site:

dart
(int min, int max) range(List<int> xs) {
  var sorted = [...xs]..sort();
  return (sorted.first, sorted.last);
}

final (lo, hi) = range([4, 1, 9]); // lo = 1, hi = 9

Tip: Keep functions short and focused. In Flutter, a long build method is often a sign you should extract a helper widget.

Test yourself

How do you call void f({required int size})?

  1. f(10)
  2. f(size: 10)
  3. f([10])
  4. f(required: 10)

What is int sq(int x) => x * x; equivalent to?

  1. int sq(int x) { x * x; }
  2. int sq(int x) { return x * x; }
  3. void sq(int x) { print(x * x); }
  4. A variable named sq

Why do closures created by separate calls to makeCounter() count independently?

  1. Dart copies functions
  2. Each call creates a new local variable the closure captures
  3. Closures can't modify variables
  4. Because count is const