Dart 有两种传参方法:位置参数和命名参数。位置参数你可能会比较熟悉:
int sumUp(int a, int b, int c) {
return a + b + c;
}
// ···
int total = sumUp(1, 2, 3);
在 Dart 里,你可以将这些参数包裹在方括号中,使其变成可选位置参数:
int sumUpToFive(int a, [int? b, int? c, int? d, int? e]) {
int sum = a;
if (b != null) sum += b;
if (c != null) sum += c;
if (d != null) sum += d;
if (e != null) sum += e;
return sum;
}
// ···
int total = sumUpToFive(1, 2);
int otherTotal = sumUpToFive(1, 2, 3, 4, 5);
可选位置参数永远放在方法参数列表的最后。除非你给它们提供一个默认值,否则默认为 null:
int sumUpToFive(int a, [int b = 2, int c = 3, int d = 4, int e = 5]) {
// ···
}
// ···
int newTotal = sumUpToFive(1);
print(newTotal); // <-- prints 15
看练习:
实现一个名为 joinWithCommas 的方法,它接收一至五个整数,然后返回由逗号分隔的包含这些数字的字符串。以下是方法调用和返回值的一些示例:
方法调用 返回值
joinWithCommas(1) ‘1’
joinWithCommas(1, 2, 3) ‘1,2,3’
joinWithCommas(1, 1, 1, 1, 1) ‘1,1,1,1,1’
答案:
String joinWithCommas(int a, [int? b, int? c, int? d, int? e]) {
var total = '$a';
if (b != null) total = '$total,$b';
if (c != null) total = '$total,$c';
if (d != null) total = '$total,$d';
if (e != null) total = '$total,$e';
return total;
}