Functions Basics
Declaring functions, return types, arrow syntax, and functions as first-class values.
阅读需 2 分钟
You've already used one function in every lesson so far — main(). Dart treats functions as regular, first-class citizens: they can be declared at the top level, take typed parameters, return typed values, and even be passed around like any other value.
Declaring a function
int add(int a, int b) {
return a + b;
}
void main() {
print(add(2, 3)); // 5
}The return type (int) comes before the name, parameters are typed just like variables, and void marks a function that doesn't return a value. Dart's analyzer checks that every code path through a non-void function actually returns something of the declared type — return the wrong type, or forget to return at all, and it won't compile.
Arrow syntax
When a function's body is a single expression, => lets you skip the { return ...; } wrapper entirely:
int square(int x) => x * x;
bool isEven(int n) => n % 2 == 0;
print(square(5)); // 25
print(isEven(4)); // trueint square(int x) => x * x; is exactly equivalent to writing out { return x * x; } — it's not a different kind of function, just a shorter way to write one whose entire job is a single expression. Use it freely for small, expression-shaped functions; once a body needs more than one statement, switch back to the full block form.
Functions as values
Because functions are values in Dart, you can store one in a variable, pass it as an argument, or return it from another function:
void greet(String name) {
print('Hello, $name!');
}
void main() {
// Store a function in a variable
void Function(String) sayHello = greet;
sayHello('Maya'); // Hello, Maya!
// Pass a function as an argument
final numbers = [1, 2, 3, 4, 5];
final doubled = numbers.map((n) => n * 2).toList();
print(doubled); // [2, 4, 6, 8, 10]
}(n) => n * 2 is an anonymous function (a lambda) — it has no name of its own and exists just to be handed to .map(). This pattern shows up everywhere once you start working with collections: instead of writing a loop, you describe what transformation to apply, and a method like .map(), .where(), or .forEach() handles the iteration for you.
Why this matters beyond syntax
Treating functions as ordinary values is what makes callbacks, event handlers, and functional-style collection operations possible without any special language feature beyond "a function is just another kind of value." It's also the foundation async/await builds on later in this course — an asynchronous operation is, underneath, just a function whose result you receive later rather than immediately.