Dart Programming - Boolean


Advertisements

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.

Useful Video Courses


Video

Dart tutorial for Beginners

44 Lectures 4.5 hours

Sriyank Siddhartha

Video

Flutter Tutorial for Beginners with Dart

34 Lectures 4 hours

Sriyank Siddhartha

Video

Dart Masterclass Programming: iOS/Android Bible

69 Lectures 4 hours

Frahaan Hussain

Video

Flutter & Dart Development For Building iOS and Android Apps

117 Lectures 10 hours

Frahaan Hussain

Video

COMPLETE Google DART Programming- BOOTCAMP

22 Lectures 1.5 hours

Pranjal Srivastava

Video

AWS Mobile with Google Dart

34 Lectures 3 hours

Pranjal Srivastava

Advertisements