Dart: Functions
What you will learn
How to define functions, use arrow syntax for short bodies, and work with optional parameters.
Basic function
String greet(String name) {
return 'Hello, $name!';
}
void main() {
print(greet('Alice'));
}
Syntax: return type, function name, parameters with types, body in { }. void means no return value.
Arrow functions (single expression)
int add(int a, int b) => a + b;
String greet(String name) => 'Hello, $name!';
=> expr is shorthand for { return expr; }. Use it when the function body is a single expression.
Optional positional parameters
Wrap in [ ] to make parameters optional:
String greet(String name, [String? greeting]) {
var g = greeting ?? 'Hello';
return '$g, $name!';
}
greet('Alice'); // Hello, Alice!
greet('Alice', 'Hi'); // Hi, Alice!
Named parameters
Wrap in { } for named (keyword) parameters:
void configure({String? host, int port = 8080}) {
print('$host:$port');
}
configure(host: 'localhost', port: 3000);
configure(port: 4000);
Named parameters are optional by default. Use required to make them mandatory:
void register({required String username, required String email}) { } // both required
Common mistakes
- Forgetting
requiredon a named parameter that must always be provided - Using
=>for multi-statement functions —=>only works for single expressions - Confusing
[ ](optional positional) with{ }(named parameters) - Forgetting that
voidfunctions cannot be used in expressions
Quick check below!