Dart Boolean Tutorial with Examples
1. Boolean
In the Dart programming language, bool is a supported data type, which only includes 2 values, true and false.
bool is also the name of the class representing this data type.
Syntax to declare a variable of bool type:
bool myVariable1 = true;
bool myVariable2 = false;
Example:
bool_ex1.dart
void main() {
bool value;
value = 100 > 25;
print(value); // true
}
Output:
true
2. Dart Boolean vs Javascript Boolean
No ADS
The Dart programming language borrows a lot of ideas from JavaScript, which is why it is so easily converted into JavaScript code. However, the bool data type in Dart and JavaScript has a few differences.
- In JavaScript the values false, 0, "", null, undefined, NaN and Number.Infinite are considered false. Other values are considered true.
- In Dart, only true and false are considered bool, other values cannot be converted to bool.
In JavaScript you can write code like below, which is accepted as valid:
Javascript code
var test = "abc";
if(test) {
console.log("OK! test is true");
} else {
console.log("Ohh no, test is false");
}
Output:
OK! test is true
However, you can't write a similar code in Dart:
Dart code (ERROR!)
void main() {
var test = "abc";
if (test) { // ERROR at compile time.
print("OK! test is true");
} else {
print("Ohh no, test is false");
}
}
You will get an error message from the Dart compiler:
Error compiling to JavaScript:
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:4:7:
Error: A value of type 'String' can't be assigned to a variable of type 'bool'.
if (test) { // ERROR at compile time.
^
Error: Compilation failed.
No ADS
Dart Programming Tutorials
- Dart dot dot ( .. ) operator
- Install Dart Code Extension for Visual Studio Code
- Dart Closures Tutorial with Examples
- Install Dart SDK on Windows
- Install Dart Plugin for Android Studio
- Dart Boolean Tutorial with Examples
- Dart Properties Tutorial and Examples
- Dart List Tutorial with Examples
- Dart dart_json_mapper Tutorial with Examples
- Parsing JSON with dart:convert
- Run your first Dart example in Android Studio
- Dart methods Tutorial and Examples
- Install Visual Studio Code on Windows
- Run your first Dart example in Visual Studio Code
- Dart programming with DartPad online tool
- Dart Variables Tutorial with Examples
- Dart Loops Tutorial with Examples
- Dart Map Tutorial with Examples
- What is Transpiler?
- Dart Functions Tutorial with Examples
Show More