📜  Dart编程-布尔

📅  最后修改于: 2020-11-05 04:17:20             🧑  作者: Mango


Dart对Boolean数据类型提供了内置支持。 DART中的布尔数据类型仅支持两个值– true和false。关键字bool用于表示DART中的布尔字面量。

在DART中声明布尔变量的语法如下所示-

bool var_name = true;  
OR  
bool var_name = false 

void main() { 
   bool test; 
   test = 12 > 5; 
   print(test); 
}

它将产生以下输出

true 

与JavaScript不同,布尔数据类型仅将字面量true识别为true。任何其他值都被视为false。考虑以下示例-

var str = 'abc'; 
if(str) { 
   print('String is not empty'); 
} else { 
   print('Empty String'); 
} 

上面的代码中,如果在JavaScript中运行,将打印信息“字符串不空”的,如果,如果该字符串不为空结构将返回true。

但是,在Dart中,将str转换为false,因为str!= true 。因此,该代码段将打印消息“空字符串” (在未检查模式下运行时)。

上面的代码段如果以选中模式运行,将引发异常。如下图所示-

void main() { 
   var str = 'abc'; 
   if(str) { 
      print('String is not empty'); 
   } else { 
      print('Empty String'); 
   } 
}

Checked模式下,它将产生以下输出

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. (dart:isolate-patch/isolate_patch.dart:261) 
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)

它将在Unchecked模式下产生以下输出

Empty String

注意-默认情况下, WebStorm IDE在检查模式下运行。