Dart基礎(三)

級別: ★☆☆☆☆
標簽:「Flutter 」「Dart」「Dart Operator」「Dart Exceptions」
作者: WYW
審校: QiShare團隊


前言:
4篇Dart基礎已經全部更新完成。目錄如下:
Dart 基礎 (一)
Dart 基礎 (二)
Dart 基礎 (三)
Dart 基礎 (四)

本文是Dart基礎的第3篇,在本文中,筆者會主要介紹2部分內容,運算符和異常。

1 Operator(運算符)主要分如下4部分

  • 1.1 算數運算符
  • 1.2 級聯運算符
  • 1.3 類型判定運算符
  • 1.4 其他運算符

2 異常主要分如下4部分

  • 2.0 Try
  • 2.1 Throw
  • 2.2 Catch
  • 2.3 Finally

詳情如下:

Dart中可能遇到的運算符如下圖所示:

運算符.png

上述運算符中,筆者不大熟悉的運算符有:

  • 算數運算符:~/
  • 賦值運算符:??
  • 級聯運算符:..
  • 類型判定運算符:asisis!
  • 其他運算符:?.

如果你對其他運算符不大熟悉,可以查看Dart文檔

1.1 算數運算符
  • ~/: 整除;

整除的結果是 運算符左側的數 除以 運算符右側的數 可以商幾。

5 ~/ 2 = 2;
7 ~/ 3 = 2;
9 ~/ 3 = 0;
  • 賦值運算符:??
String qiShare1 = 'qiShare1';
String qiShare2;
qiShare2 ??= qiShare1;
print(qiShare2);

// 輸出結果
qiShare1

1.2 級聯運算符

  • 級聯運算符:..

.. 級聯運算符

class QiCascade {
  String firstProperty;
  String secondProperty;
  String thirdProperty;
  String fourthProperty;
}

class QiSubCascade extends QiCascade{
  
}

void main() {
  
  QiCascade cascade = QiCascade();
  cascade.firstProperty = 'firstPropertyValue';
  cascade.secondProperty = 'secondPropertyValue';
  cascade.thirdProperty = 'thirdPropertyValue';
  cascade.fourthProperty = 'fourthPropertyValue';

  print('輸出屬性:${cascade..firstProperty
  ..secondProperty
  ..thirdProperty
  ..fourthProperty}');
  print('級聯輸出:');
  print(cascade..firstProperty..secondProperty..thirdProperty..fourthProperty);
  print('屬性:${cascade.firstProperty}');
  
  print(cascade.firstProperty);
  print(cascade.secondProperty);
  print(cascade.thirdProperty);
  print(cascade.fourthProperty);

  cascade..firstProperty = 'changedFirstPropertyValue'
  ..secondProperty = 'changedSecondPropertyValue'
  ..thirdProperty = 'changedThirdPropertyValue'
  ..fourthProperty = 'changedFourthPropertyValue';

  print('級聯輸出:${cascade..firstProperty
  ..secondProperty
  ..thirdProperty
  ..fourthProperty}');
}

輸出結果

flutter: 輸出屬性:Instance of 'QiCascade'
flutter: 級聯輸出:
flutter: Instance of 'QiCascade'
flutter: 屬性:firstPropertyValue
flutter: firstPropertyValue
flutter: secondPropertyValue
flutter: thirdPropertyValue
flutter: fourthPropertyValue
flutter: 級聯輸出:Instance of 'QiCascade'

看起來級聯運算符可以用于同時操作并列的實例變量。

1.3 類型判定運算符

  • 類型判定運算符:asisis!
操作符 解釋
as 類型轉換
is 如果對象是指定的類型返回true
is! 如果對象是指定的類型返回false
  dynamic subCascade = QiSubCascade();
  
  if (subCascade is QiCascade) {
    subCascade.firstProperty = 'isQiCascadeFirstPropertyValue';
  }
  print('subCascade屬性:${subCascade.firstProperty}');
  print('subCascade runtimeType:${subCascade.runtimeType}');

  if(subCascade.runtimeType == QiSubCascade) {
    print('subCascade的runtimeType為 ${subCascade.runtimeType}');
  }
  
  (subCascade as QiCascade).firstProperty = 'asQiCascadeFirstPropertyValue';
  print('subCascade屬性:${subCascade.firstProperty}');

使用 is 和 as 的區別在于:

  • 使用is:如果上述subCascade不是QiCascade,則條件中的賦值代碼不會執行
  • 使用as:如果上述subCascade為null 或者不是QiCascade類型,則運行過程中會拋出異常。

輸出結果

flutter: subCascade屬性:isQiCascadeFirstPropertyValue
flutter: subCascade runtimeType:QiSubCascade
flutter: subCascade的runtimeType為 QiSubCascade
flutter: subCascade屬性:asQiCascadeFirstPropertyValue

1.4 其他運算符

運算符 名字 解釋
() 使用方法 代表調用一個方法。
[] 訪問List 訪問list 中特定位置的元素。
. 訪問Member 訪問元素,如上邊我們訪問cascade.firstProperty。
?. 條件成員訪問 和 . 類型, 但是.左邊操作對象不能為null,否則拋出異常,?.左邊的操作對象可以為null,返回null。
subCascade = null;
  
  try {
    print('賦值null 后訪問成員 ${subCascade.firstProperty}');
  } catch (e) {
    print('異常信息 $e');
  }
  
  print('賦值null 后訪問成員 ${subCascade?.firstProperty}');

輸出結果

flutter: 異常信息 NoSuchMethodError: The getter 'firstProperty' was called on null.
Receiver: null
Tried calling: firstProperty
flutter: 賦值null 后訪問成員 null

如果我們使用條件成員訪問運算符?.。就不會有上述異常。

  • 其他運算符:?.: 條件成員訪問,如果操作符左側的實例存在,則會取值 ;

    如qiShare?.name,如果qiShare 不為null,則返回結果為qiShare.name。否則返回結果為null。

subCascade = null;
subCascade ?. firstProperty;

異常

常見的異常有 FormatException格式異常、HttpException網絡異常、FileSystemException操作文件的異常、越界的異常,操作的實例調用了沒有實現的方法 的異常。

2.1 Try

try 用于包含可能出現異常的代碼

2.2 Throw

throw 用于拋出異常。

2.3 Catch

Catch 用于捕獲異常,可以防止異常繼續傳遞。除非使用了rethrow 會將捕獲的異常再次拋出。

筆者先舉了2個特定的異常例子FormatException 、IntegerDivisionByZeroException

1.FormatException,在把字符串'123?4B'轉為數字的時候出現的類型轉換異常。

var numValue = '123?4B';
    try {
      int numValueInt = int.parse(numValue);
      print(numValueInt);
    } on FormatException catch (e){
      print('出現FormatException: $e');
        // rethrow; 使用rethrow 會將catch 住的異常再次拋出 
    } on Exception catch(e) {
      print('Exception: $e');
      // rethrow; 使用rethrow 會將catch 住的異常再次拋出 
    } 

    // 輸出結果:
    /*
    flutter: 出現FormatException: FormatException: Invalid radix-10 number (at character 1)
123\^]4B
     */

2.IntegerDivisionByZeroException 在0作除數的時候出現的異常。整除出現。

     // double zeroValue = 0.0; // 如果使用0.0 則IntegerDivisionByZeroException 不會捕獲
     int zeroValue = 0;
    int num1 = 1;
    try {
      print(num1 ~/ zeroValue); // 會觸發異常 但是也不是除0異常
      // print(num1 / zeroValue); // 不會觸發異常
    } on IntegerDivisionByZeroException catch(e) {
      print('除以0異常:$e');
    } catch (e) {
      print('異常信息:$e');
    }
    // 輸出結果
     flutter: 除以0異常:IntegerDivisionByZeroException

下邊筆者又列舉了其他的幾個異常的例子。

// 拋出異常示例
  try {
    throw Exception(
    'Custom Exception'
    );
  } catch (e) {
    print(e);
  }

  try {
    throw '自定義字符串Exception';
  } catch (e) {
    print(e);
  }
  
  List list1 = ['QiShare'];
  try {
    print(list1[1]);  
  } catch (e) {
    print(e);
  }

  try {
    (list1 as QiCascade).firstProperty;
  } catch (e) {
    print(e);
  }

  list1 = null;
  try {
    print(list1[1]);  
  } catch (e) {
    print(e);
  }

  try {
    (list1 as QiCascade).firstProperty;
  } catch (e) {
    print(e);
  }

輸出結果

flutter: Exception: Custom Exception
flutter: 自定義字符串Exception
flutter: RangeError (index): Invalid value: Only valid value is 0: 1
flutter: type 'List<dynamic>' is not a subtype of type 'QiCascade' in type cast
flutter: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: [](1)
flutter: NoSuchMethodError: The getter 'firstProperty' was called on null.
Receiver: null
Tried calling: firstProperty

針對上述代碼的異常捕獲,筆者發現,catch不僅可以捕獲異常也可以捕獲Error,筆者Dart 的Exceptions 包括Exception 和 Error。并且對如上代碼中RangeError、NoSuchMethodError的代碼做了如下處理:

捕獲RangeError

List list1 = ['QiShare'];
    try {
      print(list1[1]);  
    } on RangeError catch(error) {
      print('RangeError錯誤:$error');
    } catch (e) {
      print(e.runtimeType);
      print(e);
    }
    // 輸出結果:
    /*
    flutter: RangeError錯誤:RangeError (index): Invalid value: Only valid value is 0: 1
    */
    

捕獲NoSuchMethodError

List list1;
    try {
      print(list1[1]);  
    } on NoSuchMethodError catch(noSuchMethodError){
      print('NoSuchMethodError錯誤:$noSuchMethodError');
    } catch (e) {
      print('異常信息:$e');
    }

    // 輸出結果:
    /**
     * flutter: NoSuchMethodError錯誤:NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: [](1)
     */

2.4 Finally

Finally 部分的代碼,不管是否有出現異常,都會執行,如果出現了異常,則執行完catch中的代碼后,會執行Finally 中的代碼,如果沒有出現異常,則執行完了try中的代碼后,會執行Finally 中的代碼。

    List list1;
    try {
      print(list1[1]);  
    } on NoSuchMethodError catch(noSuchMethodError){
      print('NoSuchMethodError錯誤:$noSuchMethodError');
    } catch (e) {
      print('異常信息:$e');
    } finally {
      print('執行Finally 中的代碼');
    }
    
    
 /**
     * flutter: NoSuchMethodError錯誤:NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: [](1)
flutter: 執行Finally 中的代碼
     */

還有一種情況是try 中的代碼出現了異常,但是沒有使用catch 進行異常捕獲。但使用了finally 語句。像這種情況,出現異常的情況下,會先執行finally 中的代碼,然后拋出異常。
代碼如下:

    List list3;
    try {
      print(list3[1]);  
    } finally {
      print('執行Finally 中的代碼');
    }
    
    // 輸出結果:
    
    /**
    flutter: 執行Finally 中的代碼
flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
flutter: The following NoSuchMethodError was thrown while handling a gesture:
flutter: The method '[]' was called on null.
flutter: Receiver: null
flutter: Tried calling: [](1)
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
省略............
    */

參考學習網址


推薦文章:
Dart基礎(一)
Dart基礎(二)
iOS 短信驗證碼倒計時按鈕
iOS 環境變量配置
iOS 中處理定時任務的常用方法
算法小專欄:貪心算法
iOS 快速實現分頁界面的搭建
iOS 中的界面旋轉

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Dart重要概念:1,在變量中可以放置的所有東西都是對象,而每個對象都是類的實例。無論數字、函數、和null都是對...
    哥哥是歐巴Vitory閱讀 829評論 0 1
  • 此文章是v1.0+時編寫,年代久遠,小心有毒,謹慎食用!!! 一些重要概念 所有的東西都是對象,所有的對象都是類的...
    soojade閱讀 10,113評論 2 27
  • 標簽(空格分隔): Dart Flutter Dart在靜態語法方面和Java非常相似,如類型定義、函數聲明、泛型...
    黃昭鴻閱讀 436評論 0 0
  • Dart重要的概念 所有的東西都是對象,無論是變量、數字、函數都是對象。所有的對象都是類的實例。所有的對象都繼承自...
    JeromeWang閱讀 1,123評論 1 1
  • 雖然你會因為我一時的離開傷心,但最后你會恨我會忘了我,然后過著自己的幸福生活,我在遠處知道你過得很幸福也就行了,我...
    白澤liwzh閱讀 366評論 0 0