We'll continue with the same pattern from the previous recipe:
- Start by creating the hub function for the different features we are going to cover:
void functionPlayground() {
classicalFunctions();
optionalParameters();
}
- Now, add some functions that take parameters and return values:
void printMyName(String name) {
print('Hello $name');
}
int add(int a, int b) {
return a + b;
}
int factorial(int number) {
if (number <= 0) {
return 1;
}
return number * factorial(number - 1);
}
void classicalFunctions() {
printMyName('Anna');
printMyName('Michael');
final sum = add(5, 3);
print(sum);
print('10 Factorial is ${factorial(10)}');
}
- One of the new features that Dart has added is optional parameters. If you wrap your function's parameter list in square brackets, then those parameters can be omitted without the compiler throwing errors.
The question mark after a parameter, such as in String? name, tells the Dart compiler that the parameter itself can be null.
- Write this code immediately after the previous example:
void unnamed([String? name, int? age]) {
final actualName = name ?? 'Unknown';
final actualAge = age ?? 0;
print('$actualName is $actualAge years old.');
}
Dart also supports named optional parameters, with curly brackets.
When calling a function with named parameters, you need to specify the parameter name. You can call the parameters in any order; for example, named(greeting: 'hello!');.
- Add this function right after the unnamed optional function:
void named({String? greeting, String? name}) {
final actualGreeting = greeting ?? 'Hello';
final actualName = name ?? 'Mystery Person';
print('$actualGreeting, $actualName!');
}
- Optional parameters and optional named parameters also support default values. If the parameter is omitted when the function is called, the default value will be used instead of null. You can also place a set of required parameters first, followed by a list of optionals. Add the following code to see how this can be accomplished:
String duplicate(String name, {int times = 1}) {
String merged = '';
for (int i = 0; i < times; i++) {
merged += name;
if (i != times - 1) {
merged += ' ';
}
}
return merged;
}
- Now, implement the playground function to show all these pieces in action:
void optionalParameters() {
unnamed('Huxley', 3);
unnamed();
// Notice how named parameters can be in any order
named(greeting: 'Greetings and Salutations');
named(name: 'Sonia');
named(name: 'Alex', greeting: 'Bonjour');
final multiply = duplicate('Mikey', times: 3);
print(multiply);
}
- Finally, update the main method so that these functions can be executed:
main() {
variablePlayground();
stringPlayground();
functionPlayground();
}