目录

dart_programming编程 - 布尔值(Boolean)

Dart为布尔数据类型提供内置支持。 DART中的布尔数据类型仅支持两个值 - true和false。 关键字bool用于表示DART中的布尔文字。

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

bool var_name = true;  
OR  
bool var_name = false 

例子 (Example)

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

它将产生以下output -

true 

例子 (Example)

与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 as str != true 。 因此,代码段将打印消息'Empty String' (在未选中模式下运行时)。

例子 (Example)

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

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

它将在Checked Mode产生以下output -

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)

它将以Unchecked Mode生成以下output -

Empty String

Note - 默认情况下, WebStorm IDE以选中模式运行。

↑回到顶部↑
WIKI教程 @2018