Functions
Prerequisites: Lists
A function is a named, reusable block of code that performs a task.
Real-world analogy: a function is a recipe. You write the steps once, then just say "make pancakes" whenever you want them.
Syntax
ReturnType name(Type parameter) {
// code
return value;
}
Example
String greet(String name) {
return 'Hello, $name!';
}
void main() {
print(greet('Ada'));
print(greet('Linus'));
}
Expected output
Hello, Ada!
Hello, Linus!
- The return type (
String) comes first;voidmeans no value is returned. - Each parameter has a type and a name.
returnsends the result back to the caller.
Arrow functions
A function that just returns one expression can use =>:
int square(int n) => n * n;
bool isAdult(int age) => age >= 18;
void main() {
print(square(7));
print(isAdult(16));
}
49
false
Functions without a return value
void printBanner(String text) {
print('*** $text ***');
}
void main() {
printBanner('Sale');
}
*** Sale ***
Functions can be declared before or after main in the file.
Common mistakes
- Declaring a return type but forgetting
returnon some path — Dart reports that the function might complete without returning a value. - Passing the wrong type:
square('7')doesn't compile.
Practice
Write double area(double width, double height) and
bool isSquare(double width, double height). Print both for a 4 by 4
rectangle.
Show solution
double area(double width, double height) => width * height;
bool isSquare(double width, double height) => width == height;
void main() {
print(area(4, 4));
print(isSquare(4, 4));
}
16.0
true