Sub topic 6
Functions, named parameters, and closures
Assume you know variables, expressions, conditionals, and basic object-oriented programming. This chapter focuses on how Dart defines, passes, and stores behavior in functions.
Declaring and calling functions
A function is a named block of code that can receive values and return a result. Dart supports return types, parameter types, expression-bodied functions, and inferred local types.
String greet(String name, {String greeting = 'Hello'}) =>
'$greeting, $name!';
void main() {
print(greet('Ada'));
print(greet('Ada', greeting: 'Hi'));
}greet has one required positional parameter, name. Positional arguments are matched by their order. The greeting parameter is named because it appears inside {}. Its default value is used when the caller does not provide it.
The function returns a String, so its return type appears before its name. The arrow (=>) introduces an expression-bodied function. The expression after the arrow is returned automatically.
A block-bodied function uses braces and an explicit return when it produces a value:
int add(int left, int right) {
final result = left + right;
return result;
}A function returning no useful value normally uses void.
Parameter choices
Dart has several parameter forms:
| Form | Example | Calling style |
|---|---|---|
| Required positional | `String greet(String name)` | `greet('Ada')` |
| Optional positional | `String join(String a, [String b = ''])` | `join('A')` |
| Named with a default | `greet(String name, {String greeting = 'Hello'})` | `greet('Ada')` |
| Required named | `greet({required String name})` | `greet(name: 'Ada')` |
Optional positional parameters use square brackets. They must come after all required positional parameters. Named parameters are often clearer when a value has a specific role, especially in Flutter widget constructors.
Use required when a named argument must be supplied:
void logMessage({required String message, bool urgent = false}) {
print(urgent ? 'URGENT: $message' : message);
}Dart checks these calls at compile time. logMessage() is invalid because message is required.
Closures and function values
A closure is a function value that can be stored in a variable, passed to another function, or returned from a function. A closure can access variables from the surrounding scope. This captured environment is called lexical scope.
int apply(int value, int Function(int) operation) {
return operation(value);
}
void main() {
final multiplier = 3;
final triple = (int value) => value * multiplier;
print(apply(4, triple));
print(apply(5, (value) => value + 10));
}int Function(int) describes a function that accepts an int and returns an int. The closure assigned to triple captures multiplier. The anonymous function passed to apply is another closure.
You can pass a named function without calling it. This is called a function tear-off:
int square(int value) => value * value;
void main() {
final values = [1, 2, 3];
final squares = values.map(square).toList();
print(squares);
}map receives the function itself. Writing map(square()) would be an error because it calls square immediately and passes its result instead of passing a function.
Common errors
- Omitting a
requirednamed argument. - Passing positional arguments in the wrong order.
- Calling a function when a callback is expected.
- Capturing mutable variables and assuming the closure stores a copy.
- Using a nullable parameter without checking it before access.
Exercise
Rewrite String label(String text, [String prefix]) so that the prefix is a named optional parameter with the default value "Item".
Show answer
String label(String text, {String prefix = 'Item'}) => '$prefix: $text';