函數(shù)簡(jiǎn)單使用
我們定義一個(gè)函數(shù),并調(diào)用看看
// 一切都是對(duì)象
->「這個(gè)Function方法沒(méi)辦法表示傳入的參數(shù),返回值是什么」
void fun(Function f) {
f(1,2);
}
void main() {
Function f = fun;
->「這里是傳入一個(gè)閉包c(diǎn)losure,也可以叫l(wèi)ambada,匿名函數(shù)等」
f((int i, int j) {
return "1";
});
}
但是這么做似乎,調(diào)用者很茫然,他相當(dāng)于這么定義
void fun3(void f1(int i, int j)) {}
但dart里面里有更好的方式:「typedef 定義一個(gè)函數(shù)類(lèi)型」
typedef String F(int i, int j);
String fun4(F f) {
return f(1, 1);
}
應(yīng)用場(chǎng)景
// 對(duì)比java,需要定義一個(gè)接口,然后傳入接口
class OnCicklistener {
void onClick() {}
}
class Button {
void setOnClicklistener(OnCicklistener onCicklistener) {}
}
// dart 定義一個(gè)函數(shù),傳函數(shù)
typedef void onClick();
class Button2 {
void setOnClicklistener(onClick listener) {
listener();
}
}
可選位置參數(shù)
// 可選位置參數(shù)
-> 「理解上可以想象數(shù)組,按順序傳遞參數(shù),也可以給默認(rèn)的值」
void fun5([int i,int j = 2]){
print(i);
print(j);
}
調(diào)用可以,如下
fun5(3);
fun5(3,5);
可選命名參數(shù)
// 可選命名參數(shù)
-> 這個(gè)參數(shù)傳值不考慮順序,但是每個(gè)參數(shù)必須K:V 的方式傳值,可以有默認(rèn)值
void fun6({int i,int j = 2}){
print(i);
print(j);
}
調(diào)用 ->
fun6(i:3,j:0);
fun6(j:6,i:300);
應(yīng)用場(chǎng)景:不需要寫(xiě)大量的重載函數(shù),類(lèi)似java一樣,可以給默認(rèn)值 比如構(gòu)造函數(shù),dart一個(gè)方法搞定一切
異常
「需要注意的是」->Dart & Kotlin 類(lèi)似,不會(huì)主動(dòng)提示你try-catch,需要你自己添加
作為實(shí)驗(yàn),我們定義幾個(gè)函數(shù)
void testStr(String str){
print(str);
}
void test(){
throw Exception("你太帥不給你調(diào)用");
}
void test2(){
throw "你太帥不給你調(diào)用";
}
void test3(){
throw 111;
}
int test4(int i){
if(i == 0){
throw "000000";
} else if(i == 1) {
throw 1;
} else if(i == 2){
throw testStr;
}
->「拋出異常還可以返回」
return i;
}
catch 最多接受兩個(gè)參數(shù),exception & stack
try {
test();
->「exception,StackTrace」
} catch (e,s) {
print(e);
print(e.runtimeType);
print(s);
print(s.runtimeType);
}
按照異常類(lèi)型進(jìn)行過(guò)濾處理
-> on Type catch...
try {
// test();
// test2();
test3();
} on Exception catch (e,s) {
print("Exception......lll");
print(e);
print(e.runtimeType);
print(s);
print(s.runtimeType);
} on int catch(e) {
print("int");
print(e);
} on String catch(e){
print("String");
print(e);
}
捕獲異??梢岳^續(xù)調(diào)用函數(shù)處理
try {
int i = test4(3);
if(i == 3) {
print('return .......');
}
} on Function catch (e,s) {
e("騷操作");
} on String catch(e) {
print(e);
} on int catch(e){
print(e);
} finally{
-> 「最終這里執(zhí)行,和java一樣」
}