Named and Optional Parameters
Prerequisites: Functions
Dart functions support named and optional parameters — you'll see them in almost every Flutter widget.
Named parameters
Named parameters go inside { } and are passed by name, in any order:
String createUser({required String name, String role = 'member', bool active = true}) {
return '$name ($role, active: $active)';
}
void main() {
print(createUser(name: 'Ada'));
print(createUser(name: 'Linus', active: false));
print(createUser(role: 'admin', name: 'Grace'));
}
Ada (member, active: true)
Linus (member, active: false)
Grace (admin, active: true)
- Named parameters are optional unless marked
required. - An optional named parameter needs a default value, or a nullable type.
- Names make calls self-explanatory: compare
createUser('Linus', 'member', false)— what doesfalsemean?
Optional positional parameters
Parameters in [ ] are positional but optional:
String greet(String name, [String greeting = 'Hello']) => '$greeting, $name!';
void main() {
print(greet('Ada'));
print(greet('Ada', 'Welcome'));
}
Hello, Ada!
Welcome, Ada!
A function can have positional parameters followed by either optional positional or named parameters — not both.
Named parameters in Flutter
This is how Flutter widgets read:
Text(
'Hello',
style: TextStyle(fontSize: 24),
textAlign: TextAlign.center,
)
Common mistakes
- Forgetting a
requiredargument:Error: Required named parameter 'name' must be provided. - Giving an optional named parameter a non-nullable type with no default — Dart rejects it, since it could be missing.
Practice
Write String formatPrice(double amount, {String currency = 'USD'})
returning '12.5 USD'. Call it once with only an amount and once with
currency: 'EUR'.
Show solution
String formatPrice(double amount, {String currency = 'USD'}) => '$amount $currency';
void main() {
print(formatPrice(12.5));
print(formatPrice(12.5, currency: 'EUR'));
}
12.5 USD
12.5 EUR