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.
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; }.
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).
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.
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.
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:
(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 = 9Tip: Keep functions short and focused. In Flutter, a long
buildmethod is often a sign you should extract a helper widget.
Test yourself
How do you call void f({required int size})?
- f(10)
- f(size: 10)
- f([10])
- f(required: 10)
What is int sq(int x) => x * x; equivalent to?
- int sq(int x) { x * x; }
- int sq(int x) { return x * x; }
- void sq(int x) { print(x * x); }
- A variable named sq
Why do closures created by separate calls to makeCounter() count independently?
- Dart copies functions
- Each call creates a new local variable the closure captures
- Closures can't modify variables
- Because count is const