Optional parameters
- Dart course
- Beginner
- Lesson 68/116
- 5 min
Learn optional and named parameters.
Optional parameters
Dart offers two ways to make a parameter optional. Positional: wrap in square brackets, void greet(String name, [String? title]) { ... }. The caller may omit title.
Named: wrap in curly braces, void greet({required String name, String? title}) { ... }. The caller says which is which: greet(name: 'Ayşe');.
For named parameters, required means mandatory, otherwise optional. You can also give a default: String title = 'Mr.'.
Default values
You can give an optional parameter a default. Positional: void greet(String name, [String title = 'Mr.']) { ... }. If the caller omits title, 'Mr.' is used.
The same holds for named: {String title = 'Mr.'}. With a default the parameter cannot be null; therefore no ? is added.
The default must be a constant literal; it cannot be a value computed at runtime. This requires values known at compile time.
Practice Greet by name
Define a greet function with the named parameter {required String name} that does print('Hello, $name'). Add a greet(name: 'Ayşe') call inside main.
Starter code
void main() {
// define the greet function
// add a call
}Sample solution
void greet({required String name}) {
print('Hello, $name');
}
void main() {
greet(name: 'Ayşe');
}Expected output
Hello, Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the parameter types
| Term | Meaning |
|---|---|
[int? b] |
Optional positional |
{int b} |
Optional named |
{required int b} |
Required named |
int b |
Required positional |
2 How is a named parameter called?
- greet('Ayşe')
- greet(name: 'Ayşe') Correct answer
- greet(name = 'Ayşe')
- greet(name -> 'Ayşe')
Explanation: named parameters are called as name: value.
3 Named parameter definition
void greet({____}) { print(name); }
void greet({required String name}) { print(name); }
Explanation: required marks a mandatory named parameter.