Sub topic 6
Functions, named parameters, and closures
This chapter assumes you know Dart's variables and types, null safety (?, ??), and basic control flow from earlier chapters. It also assumes you have used functions in another language. The chapter covers how Dart declares functions, its three kinds of parameters, functions as values, and closures.
Declaring functions
A Dart function states a return type, a name, a parameter list, and a body.
int add(int a, int b) {
return a + b;
}
int square(int x) => x * x;
void logLine(String message) => print('[log] $message');
void main() {
print(add(2, 3));
print(square(4));
logLine('ready');
}The arrow form => expr is shorthand for { return expr; }. It takes exactly one expression, not a statement. Functions can be top-level, as above, or members of classes, or nested inside other functions.
Two rules matter in practice:
- A function with a non-nullable return type must return a value on every path. Otherwise the analyzer reports an error.
- If you omit the return type, the type becomes
dynamic. This silently disables type checking. Always write the return type, and turn on thealways_declare_return_typeslint.
Positional parameters
Parameters without braces are required positional parameters. Callers must pass them in order. Wrapping parameters in square brackets makes them optional positional.
String join(String first, [String? second, String separator = '-']) {
if (second == null) return first;
return '$first$separator$second';
}
void main() {
print(join('a'));
print(join('a', 'b'));
print(join('a', 'b', '+'));
}An optional parameter must either be nullable or have a default value. The default must be a compile-time constant. [int count] with no default is a compile error. Optional positional parameters work for one or two obvious extras. Beyond that, call sites like join('a', null, '+') become hard to read, and named parameters are better.
Named parameters
Curly braces declare named parameters. Callers pass them by name, in any order, after the positional arguments.
String describe(
String name, {
required int age,
String city = 'unknown',
String? note,
}) {
final base = '$name, $age, $city';
return note == null ? base : '$base ($note)';
}
void main() {
print(describe('Ada', age: 36));
print(describe('Ada', note: 'pioneer', age: 36, city: 'London'));
}Each named parameter must satisfy one of these:
- It is marked
required. - It has a default value.
- Its type is nullable, so it defaults to
null.
A required parameter can still have a nullable type. That forces the caller to pass something, even null. A function can declare optional positional or named parameters, but not both in the same list.
Flutter widget constructors use this pattern almost everywhere. Constructors such as Text('hi', style: ..., maxLines: 2) are ordinary functions with one positional and several named parameters.
Functions are values
In Dart a function is an object. You can store it in a variable, pass it as an argument, or return it. Its type is written ReturnType Function(ParamTypes). A typedef gives that type a name.
typedef Operation = int Function(int a, int b);
int add(int a, int b) => a + b;
int apply(Operation op, int a, int b) => op(a, b);
void main() {
print(apply(add, 2, 3));
print(apply((a, b) => a * b, 2, 3));
final printer = print;
printer('tear-off works');
}Writing add without parentheses is a tear-off. It gives you the function itself instead of calling it. The tear-off print can also be passed straight to iterable methods, as in [1, 2].forEach(print).
An anonymous function (a lambda) has the form (params) { body } or (params) => expr. Dart infers the parameter types from context, so (a, b) => a * b needs no annotations above.
Avoid the bare Function type. It accepts any function, so the analyzer cannot check arguments or the return value. Use a specific function type instead.
Closures
A closure is a function that keeps access to variables from the scope where it was created, even after that scope has finished. Any Dart function that refers to an outer local variable is a closure.
int Function() makeCounter() {
var count = 0;
return () => ++count;
}
void main() {
final a = makeCounter();
final b = makeCounter();
print(a());
print(a());
print(b());
}This prints 1, 2, and 1. Each call to makeCounter creates a new count, and each returned function holds its own. The closure captures the variable, not a copy of its value at creation time. If code changes the variable later, the closure sees the new value.
Closures in loops
Languages differ on closures inside loops. In Dart, a C-style for loop creates a fresh copy of the loop variable for each iteration, so each closure captures its own value. A variable declared outside the loop is shared by all closures.
void main() {
final inFor = <void Function()>[];
for (var i = 0; i < 3; i++) {
inFor.add(() => print('for: $i'));
}
for (final f in inFor) {
f();
}
var j = 0;
final inWhile = <int Function()>[];
while (j < 3) {
inWhile.add(() => j);
j++;
}
print(inWhile.map((f) => f()).toList());
}The for closures print 0, 1, 2. The while closures all read the single shared j, which is 3 by the time they run, so the list is [3, 3, 3].
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "The parameter can't have a value of null because of its type" | A non-nullable optional parameter has no default. | Add a default, make the type nullable, or mark a named parameter `required`. |
| "The named parameter isn't defined" | The caller used a name that is not in the braces, or declared the parameter positionally. | Check the signature and the spelling. |
| "Default value must be a constant" | The default is a runtime value such as `DateTime.now()`. | Make the parameter nullable and compute the fallback in the body. |
| Function returns `null` unexpectedly | The return type is nullable or `dynamic` and one path has no `return`. | Declare a non-nullable return type so the analyzer finds the missing path. |
| All closures see the same value | They capture a variable declared outside the loop. | Declare the variable inside the loop body, or use a `for` loop variable. |
Putting it together
This example combines named parameters, a function type, and a closure to build a small configurable formatter.
typedef Formatter = String Function(String input);
Formatter makeFormatter({
required String prefix,
String suffix = '',
bool upper = false,
}) {
return (String input) {
final body = upper ? input.toUpperCase() : input;
return '$prefix$body$suffix';
};
}
void main() {
final shout = makeFormatter(prefix: '>> ', suffix: '!', upper: true);
final plain = makeFormatter(prefix: '- ');
print(shout('hello'));
print(plain('hello'));
}The returned lambda captures prefix, suffix, and upper. After makeFormatter returns, those parameters still exist inside the closure.
Exercise
What does this program print, and why? void main() { var total = 0; final add = (int n) => total += n; add(2); add(3); print(total); }
Show answer
It prints 5. The anonymous function is a closure that captures the variable total, not a copy of it. Each call to add changes the same variable that main reads afterward.
Exercise
Write a function repeat that takes a required positional String text and a named int times that defaults to 2. It returns the text repeated that many times with no separator. Then explain why {int times} without a default or required would not compile.
Show answer
String repeat(String text, {int times = 2}) => text * times; Calling repeat('ab') returns 'abab', and repeat('ab', times: 3) returns 'ababab'. The declaration {int times} fails because a named parameter is optional by default and its type int is non-nullable. If the caller omits it, the parameter would have to be null, which its type forbids. The fix is a default value, a nullable type int?, or the required keyword.