Flutter學習之Dart 中的 static 關鍵字

Dart 中的 static 關鍵字

重要點歸納

  • 使用 static 關鍵字來實現類級別的變量和函數
  • 靜態成員不能訪問非靜態成員( static 關鍵字修飾的成員 不能訪問 非 static 關鍵字修飾的成員)
  • 非靜態成員可以訪問靜態成員
  • 類中的常量是需要使用 static const 聲明

測試的基礎源碼

class Page{
  int currentPage = 1;

  void scorllDown(){
    currentPage = 1;
    print("ScrollDown...");
  }

  void scorllUp(){
    currentPage ++;
    print("ScrollUp...");
  }
}


void main(List<String> args) {
  var page = new Page();
}

報錯說明

圖:錯誤的 static 訪問

報錯一

static 修飾的靜態變量不能訪問 非static 修飾的成員

currentPage++;

正確的訪問方式:

class Page{
  // 添加 static 關鍵字
  static int currentPage = 1;

  static void scorllDown(){
    currentPage = 1;
    print("ScrollDown...");
  }

  void scorllUp(){
    currentPage ++;
    print("ScrollUp...");
  }
}

報錯二

static 修飾的成員方法爲類級別的,不能通過這樣子訪問

page.scrollDown();

正確的訪問方式:

class Page{
  static int currentPage = 1;

  static void scorllDown(){
    currentPage = 1;
    print("ScrollDown...");
  }

  void scorllUp(){
    currentPage ++;
    print("ScrollUp...");
  }
}


void main(List<String> args) {
  var page = new Page();
  // 此處修改
  Page.scorllDown();
}

報錯三

圖:類中的常量 需要使用 static const 來聲明

正確處理方式:

class Page{
  // 添加 static 關鍵字
  static const int maxPage = 10; 

  static int currentPage = 1;

  static void scorllDown(){
    currentPage = 1;
    print("ScrollDown...");
  }

  void scorllUp(){
    currentPage ++;
    print("ScrollUp...");
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章