Dart Functions
A function packages a piece of logic under a name so you can reuse it. In Dart, functions are first-class objects: you can store them in variables, pass them to other functions and return them as results.
Declaring functions
// Full syntax: return type, name, parameters, body
double average(List<int> values) {
if (values.isEmpty) return 0;
var sum = 0;
for (final v in values) {
sum += v;
}
return sum / values.length;
}
// Arrow syntax for a single expression
bool isAdult(int age) => age >= 18;
// No return value
void greet(String name) {
print('Xin chao, $name!');
}
void main() {
print(average([7, 8, 10]));
print(isAdult(16));
greet('Tam');
}8.333333333333334
false
Xin chao, Tam!
| Part | Notes |
|---|---|
| Return type | Optional but recommended for public functions. void when nothing is returned. |
| Parameters | Type name, comma-separated. Positional by default. |
=> expr |
Shorthand for { return expr; } |
| Implicit return | A function without a return returns null (its type must allow it, e.g. void). |
Functions are objects
int twice(int x) => x * 2;
int square(int x) => x * x;
void main() {
int Function(int) op = twice; // a function-typed variable
print(op(5));
op = square;
print(op(5));
var pipeline = [twice, square, twice];
var value = 3;
for (final f in pipeline) {
value = f(value);
}
print(value);
print(op is Function);
print([1, 2, 3].map(square).toList()); // passing a function by name (tear-off)
}10
25
72
true
[1, 4, 9]
Passing square without parentheses is called a tear-off: you hand over the function itself rather than calling it.
Anonymous functions (lambdas)
A function without a name: (params) { body } or (params) => expr. They're most often passed as arguments.
void main() {
var prices = [120, 45, 300, 80];
var cheap = prices.where((p) => p < 100).toList();
print(cheap);
prices.sort((a, b) {
// multi-statement body
final diff = b - a;
return diff;
});
print(prices);
var formatter = (int cents) => '\${(cents / 100).toStringAsFixed(2)}';
print(formatter(1999));
}[45, 80]
[300, 120, 80, 45]
$19.99
Higher-order functions
A function that takes or returns another function is higher-order. Function types are written ReturnType Function(ParamTypes).
// Takes a function
void repeat(int times, void Function(int) action) {
for (var i = 0; i < times; i++) {
action(i);
}
}
// Returns a function
String Function(String) makeWrapper(String left, String right) {
return (text) => '$left$text$right';
}
void main() {
repeat(3, (i) => print('tick $i'));
final bold = makeWrapper('**', '**');
final quote = makeWrapper('"', '"');
print(bold('important'));
print(quote(bold('nested')));
}tick 0
tick 1
tick 2
**important**
"**nested**"
Recursion
A function may call itself. Each call needs a base case that stops the recursion:
int factorial(int n) => n <= 1 ? 1 : n * factorial(n - 1);
int fib(int n) => n < 2 ? n : fib(n - 1) + fib(n - 2);
void main() {
print(factorial(10));
print([for (var i = 0; i < 10; i++) fib(i)]);
}3628800
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Tip: Dart doesn't optimise tail calls, so very deep recursion (tens of thousands of levels) can overflow the stack. Use a loop for long iterations.
Local functions
Functions can be declared inside other functions. They're visible only there, and they can use the outer function's variables:
String summarize(List<int> scores) {
String bucket(int s) => s >= 80 ? 'high' : 'low';
final counts = <String, int>{};
for (final s in scores) {
counts.update(bucket(s), (c) => c + 1, ifAbsent: () => 1);
}
return counts.toString();
}The next lessons cover named and optional parameters and closures.
Test yourself
What is the type of a function that takes a String and returns an int?
- Function<String, int>
- int Function(String)
- (String) -> int
- Func<String, int>
What is a tear-off?
- Calling a function with no arguments
- Using a function's name without
()to pass the function itself - Deleting a function at runtime
- A function that throws
Which is equivalent to int inc(int x) { return x + 1; }?
- int inc(int x) -> x + 1;
- int inc(int x) => x + 1;
- int inc(int x) = x + 1;
- int inc(int x): x + 1;