结论
Dart 的可选参数是可选的,因为调用者在调用函数时不需要为参数指定值。
可选参数只能在任何必需参数之后声明。
可选参数可以有一个默认值,在调用者没有指定值时使用。
位置可选参数
使用[ ]
包裹的参数是一个位置可选参数。下面是一个例子:
getHttpUrl(String server, String path, [int port=80]) { // ... }
在上面的代码中,port
是可选的,默认值为80
。
您可以getHttpUrl
使用或不使用第三个参数进行调用。
getHttpUrl('example.com', '/index.html', 8080); // port == 8080 getHttpUrl('example.com', '/index.html'); // port == 80
您可以为函数指定多个位置参数:
getHttpUrl(String server, String path, [int port=80, int numRetries=3]) { // ... }
可选参数是位置参数,如果要指定numRetries
,port
getHttpUrl('example.com', '/index.html'); getHttpUrl('example.com', '/index.html', 8080); getHttpUrl('example.com', '/index.html', 8080, 5);
当然,除非您知道 8080 和 5 是什么,否则很难说出那些看似神奇的数字是什么。您可以使用命名的可选参数来创建更具可读性的API。
命名的可选参数
使用{ }
包裹的参数是一个命名的可选参数。下面是一个例子:
getHttpUrl(String server, String path, {int port = 80}) { // ... }
可以使用或不使用第三个参数调用getHttpUrl
。但你使用第三个参数时,你必须使用参数名称调用函数。
getHttpUrl('example.com', '/index.html', port: 8080); // port == 8080 getHttpUrl('example.com', '/index.html'); // port == 80
可以为一个函数指定多个命名参数:
getHttpUrl(String server, String path, {int port = 80, int numRetries = 3}) { // ... }
因为命名参数是按名称引用的,所以它们的使用顺序可以不同于它们的声明。
getHttpUrl('example.com', '/index.html'); getHttpUrl('example.com', '/index.html', port: 8080); getHttpUrl('example.com', '/index.html', port: 8080, numRetries: 5); getHttpUrl('example.com', '/index.html', numRetries: 5, port: 8080); getHttpUrl('example.com', '/index.html', numRetries: 5);