Dart 函數(shù)

函數(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一樣」
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

友情鏈接更多精彩內(nèi)容