Dart Programming – Boolean


Dart Programming – Boolean


”;


Dart provides an inbuilt support for the Boolean data type. The Boolean data type in DART supports only two values – true and false. The keyword bool is used to represent a Boolean literal in DART.

The syntax for declaring a Boolean variable in DART is as given below −

bool var_name = true;  
OR  
bool var_name = false 

Example

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

It will produce the following output

true 

Example

Unlike JavaScript, the Boolean data type recognizes only the literal true as true. Any other value is considered as false. Consider the following example −

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

The above snippet, if run in JavaScript, will print the message ‘String is not empty’ as the if construct will return true if the string is not empty.

However, in Dart, str is converted to false as str != true. Hence the snippet will print the message ‘Empty String’ (when run in unchecked mode).

Example

The above snippet if run in checked mode will throw an exception. The same is illustrated below −

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

It will produce the following output, in Checked Mode

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)

It will produce the following output, in Unchecked Mode

Empty String

Note − The WebStorm IDE runs in checked mode, by default.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *