Dart為布爾數據類型提供內置支持,Dart中的布爾數據類型僅支持兩個值 - true
和false
。關鍵字bool
用於表示Dart中的布爾文字。
在Dart中聲明布爾變數的語法,如下所示 -
bool var_name = true;
// 或者
bool var_name = false
示例1
void main() {
bool test;
test = 12 > 5;
print(test);
}
執行上面示例代碼,得到以下結果 -
true
示例2
與JavaScript不同,布爾數據類型僅將文字true
識別為true
。任何其他值都被視為false
。考慮以下示例 -
var str = 'abc';
if(str) {
print('String is not empty');
} else {
print('Empty String');
}
如果在JavaScript中運行,上面的代碼段將列印消息 - "String is not empty"
,因為如果字串不為空,if
結構將返回true
。
但是,在Dart中,str
被轉換為false
,因為str != true
。因此,代碼段將列印消息 - "Empty String"
(在未檢查模式下運行時)。
示例3
如果以已檢查模式運行,上面的代碼片段將引發異常。如以下說明 -
void main() {
var str = 'abc';
if(str) {
print('String is not empty');
} else {
print('Empty String');
}
}
它將在已檢查模式下產生以下輸出 -
Unhandled exception:
type 'String' is not a subtype of type 'bool' of 'boolean expression' where
String is from dart:core
bool is from dart:core
#0 main (file:///D:/Demos/Boolean.dart:5:6)
#1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261)
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)
它將以檢查模式生成以下輸出 -
Empty String
注 - 默認情況下,WebStorm IDE以選中模式運行。