一、方法定義
- 方法也是對象,並且有具體類型Function
- 返回類型、參數類型都可以省略
- 箭頭語法:=> expr 是{return expr;}縮寫。只適用於一個表達式
- 方法都有返回值。如果沒有制定,默認return null左後一句執行
//方法也是對象,並且有具體類型Function
String getPerson(String name, int age){
return "名字:$name,年齡:$age";
}
printPerson(name,age){
print("名字:$name,年齡:$age");
}
//=>語法
getPerson1(name, age) => "名字:$name,年齡:$age";
print(getPerson('張三',12));
printPerson('張三',12);
print(getPerson1('張三',12));
二、可選參數
- 可選命名參數:{param1,param2,…}
- 可選位置參數:[param`,param2,…]
//1、可選命名參數{param1,...}
printPersionOptional1(name,{age,gender}) => "名字:$name,年齡:$age,性別:$gender";
//2、可選位置參數[param1,...]
printPersionOptional2(name,[age,gender]) => "名字:$name,年齡:$age,性別:$gender";
注意:可選參數必須在具體參數之後!!!
三、可選參數
- 使用=在可選參數指定默認值
- 默認值只能是編譯時常量
//默認參數
printPersionOptionalDefault(name,{age=12,gender="男"}) => "名字:$name,年齡:$age,性別:$gender";
四、對象方法
- 方法可作爲對象賦值給其他變量
- 方法可作爲參數傳遞給其他方法
void printHrello(){
print("Hello");
}
void printDoubleNumber(num){
print(num*5);
}
List listTimes(list,times(str)){
for(var index = 0; index < list.length; index ++){
list[index] = times(list[index]);
}
return list;
}
List listTimes1(list){
var fun = (str)=>str*3;
for(var index = 0; index < list.length; index ++){
list[index] = fun(list[index]);
}
return list;
}
times(str) => str*3;
Function func = printHrello;
func();
var list = [1,2,3,4];
//forEach接收一個Function類型的參數
list.forEach(print);
list.forEach(printDoubleNumber);
print(listTimes(['a','b','c','d'],times));
執行結果:
Hello
1
2
3
4
5
10
15
20
[aaa, bbb, ccc, ddd]
五、匿名方法
匿名方法特徵:
- 可賦值給變量,通過變量進行調用
- 可在其他方法中直接調用或傳遞給其他方法
//匿名方法
var func = (str){
print('======= $str');
};
func("Hlelo");
//匿名方法直接執行
((){
print('=======');
})();
print(listTimes(['a','b','c','d'],(str)=>str*5));
print(listTimes1(['a','b','c','d']));
六、閉包
- 閉包是一個方法(對象)
- 閉包定義在其他方法內部
- 閉包能夠訪問外部方法內的局部變量,並持有其狀態
a(){
int count = 0;
printCount(){
print(count++);
}
return printCount;
}
var func = a();
func();
func();
func();
func();
執行結果:
0
1
2
3
另一種寫法:
a(){
int count = 0;
// printCount(){
// print(count++);
// }
return (){
print(count++);
};
}
執行結果仍然是:
0
1
2
3