可选位置参数
本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 72 课,共 94 课。
Dart 中的可选位置参数可以让你创建带有可选参数的函数。你可以将参数放在方括号 [] 中来定义它们。
创建一个带有可选位置参数的函数:
void greet(String name, [String? greeting]) {
if (greeting != null) {
print('$greeting, $name!');
} else {
print('Hello, $name!');
}
}
void main() {
greet('Dart');
greet('Dart', 'Welcome');
}运行上面的代码后,输出将是:
Hello, Dart!
Welcome, Dart!你可以有多个可选参数:
int calculateTotal(int quantity, [int price = 10, int tax = 2]) {
return quantity * price + tax;
}
void main() {
print(calculateTotal(5));
print(calculateTotal(5, 20));
print(calculateTotal(5, 20, 5));
}运行以上代码后,输出为:
52
102
105挑战
入门在这个挑战中,你将练习在 Dart 函数中使用可选位置参数。可选位置参数可以让你创建带有可选参数的函数。
完成下面的 greet 函数。它接受一个必需的 name 参数和一个可选的 title 参数。如果提供了 title,函数应返回包含 title 和 name 的问候语。如果没有提供 title,则只使用 name。
预期输出:
Hello, John!
Hello, Dr. Smith!亲手试试
void main() {
// 这些变量已经为你定义好了
String person1 = "John";
String person2 = "Smith";
String title = "Dr.";
// 只传入名字来调用 greet 函数
print(greet(person1));
// 同时传入名字和称谓来调用 greet 函数
print(greet(person2, title));
}
// TODO:为 greet 函数添加可选的 title 参数,完成这个函数
// title 参数应为可选参数(使用方括号 [])
String greet(String name) {
// 如果提供了 title,返回 "Hello, {title} {name}!"
// 如果没有提供 title,返回 "Hello, {name}!"
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Dart 在线编译器