Dart为Boolean数据类型提供了内置支持,DART中的布尔数据类型仅支持两个值– true和false。

语法如下所示-

bool var_name=true;  
OR  
bool var_name=false 

Boolean - 示例1

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

它将产生以下输出-

true 

Boolean - 示例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"。

Boolean - 示例3

如果以上代码段以 checked 模式运行,则会引发异常。如下图所示-

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:/Learnfk/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在检查模式下运行。

参考链接

https://www.learnfk.com/dart-programming/dart-programming-boolean.html