Dart 語言簡易教程(一): http://www.reibang.com/p/8a62b1a2fd75
Dart 語言簡易教程(二): http://www.reibang.com/p/b2153a32dd8b
Dart 語言簡易教程(三)
函數(shù)(Functions)
Dart 是一個面向?qū)ο蟮恼Z言碾阁,所以即使是函數(shù)也是對象腋颠,函數(shù)屬于Function
對象柱徙。
可以通過函數(shù)來指定變量或者像其它的函數(shù)傳遞參數(shù)冒掌。
函數(shù)實現(xiàn)的例子:
bool isNoble(int atomicNumber) {
return _nobleGases[atomicNumber] != null;
}
可以去掉形式參數(shù)數(shù)據(jù)類型和返回值的數(shù)據(jù)類型罪帖。
下面的例子演示了這些:
isNoble(atomicNumber) {
return _nobleGases[atomicNumber] != null;
}
如果函數(shù)只有單個語句翩剪,可以采用簡略的形式:
bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;
The
=> expr;
syntax is a shorthand for{ return expr;}
.
函數(shù)可以有兩中類型的參數(shù):
- 必須的
必須的參數(shù)放在參數(shù)列表的前面腕柜。 - 可選的
可選的參數(shù)跟在必須的參數(shù)后面膀篮。
可選的參數(shù)
可以通過名字或位置個函數(shù)指定可選參數(shù)毯焕。
可選的名字參數(shù)
在調(diào)用函數(shù)時衍腥,可以指定參數(shù)的名字及相應(yīng)的取值,采用paramName: value
的格式纳猫。
例如函數(shù)定義:
/// Sets the [bold] and [hidden] flags to the values
/// you specify.
enableFlags({bool bold, bool hidden}) {
// ...
}
函數(shù)調(diào)用:
enableFlags(bold: true, hidden: false);
可選的位置參數(shù)
將參數(shù)使用[]
括起來紧阔,用來表明是可選位置參數(shù)。
例如下面的例子续担,函數(shù)定義:
String say(String from, String msg, [String device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
}
調(diào)用函數(shù)不包含第三個參數(shù):
assert(say('Bob', 'Howdy') == 'Bob says Howdy');
調(diào)用函數(shù)包含第三個參數(shù):
assert(say('Bob', 'Howdy', 'smoke signal') ==
'Bob says Howdy with a smoke signal');
參數(shù)默認(rèn)值
可以定義包含默認(rèn)位置參數(shù)或默認(rèn)名字參數(shù)的函數(shù)擅耽。參數(shù)的默認(rèn)值必須是編譯時的靜態(tài)值。
假如定義函數(shù)時物遇,沒有指定默認(rèn)的參數(shù)值乖仇,則參數(shù)值默認(rèn)為null
憾儒。
- 使用冒號(
:
)來設(shè)置默認(rèn)名字參數(shù)。
// Sets the [bold] and [hidden] flags to the values you
// specify, defaulting to false.
enableFlags({bool bold: false, bool hidden: false}) {
// ...
}
// bold will be true; hidden will be false.
enableFlags(bold: true);
- 使用等號(`= `)來設(shè)置默位置字參數(shù)乃沙。
```Dart
String say(String from, String msg,
[String device = 'carrier pigeon', String mood]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
if (mood != null) {
result = '$result (in a $mood mood)';
}
return result;
}
assert(say('Bob', 'Howdy') ==
'Bob says Howdy with a carrier pigeon');
也可以將lists
及maps
類型作為默認(rèn)值起趾。
如下面的例子:
doStuff({List<int> list: const[1, 2, 3],
Map<String, String> gifts: const{'first': 'paper',
'second': 'cotton',
'third': 'leather'}}) {
print('list: $list');
print('gifts: $gifts');
}
main() {
// Use the default values for both parameters.
doStuff();
// Use the default values for the "gifts" parameter.
doStuff(list:[4,5,6]);
// Don't use the default values for either parameter.
doStuff(list: null, gifts: null);
}
對應(yīng)輸出結(jié)果是:
list: [1, 2, 3]
gifts: {first: paper, second: cotton, third: leather}
list: [4, 5, 6]
gifts: {first: paper, second: cotton, third: leather}
list: null
gifts: null
main() 函數(shù)
所以的APP 都必須有一個mian()
函數(shù),作為APP 的應(yīng)用接入點警儒。
main()
函數(shù)返回void 類型训裆,并且包含可選的List< String >
類型的參數(shù)。
main()
函數(shù)不包含參數(shù)的例子:
void main() {
querySelector("#sample_text_id")
..text = "Click me!"
..onClick.listen(reverseText);
}
main()
函數(shù)包含參數(shù)的例子:
// Run the app like this: dart args.dart 1 test
void main(List<String> arguments) {
print(arguments);
assert(arguments.length == 2);
assert(int.parse(arguments[0]) == 1);
assert(arguments[1] == 'test');
}
傳遞函數(shù)給函數(shù)
-
可以將一個函數(shù)作為一個參數(shù)傳遞給另一個函數(shù)蜀铲。例如:
printElement(element) { print(element); } var list = [1, 2, 3]; // Pass printElement as a parameter. list.forEach(printElement);
-
也可以將函數(shù)賦值給一個變量边琉。例如:
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!'; assert(loudify('hello') == '!!! HELLO !!!');
變量作用范圍
嵌套的函數(shù)中可以訪問包含他的函數(shù)中定義的變量。例如:
var topLevel = true;
main() {
var insideMain = true;
myFunction() {
var insideFunction = true;
nestedFunction() {
var insideNestedFunction = true;
assert(topLevel);
assert(insideMain);
assert(insideFunction);
assert(insideNestedFunction);
}
}
}
變量閉合
函數(shù)可以返回一個函數(shù)记劝。例如:
/// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(num addBy) {
return (num i) => addBy + i;
}
main() {
// Create a function that adds 2.
var add2 = makeAdder(2);
// Create a function that adds 4.
var add4 = makeAdder(4);
assert(add2(3) == 5);
assert(add4(3) == 7);
}
函數(shù)返回值
所以的函數(shù)都會有返回值变姨。
如果沒有指定函數(shù)返回值,則默認(rèn)的返回值是null
厌丑。
沒有返回值的函數(shù)定欧,系統(tǒng)會在最后添加隱式的return 語句。