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
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.
Dart Programming Tutorials
- Dart Boolean Tutorial with Examples
- Dart Functions Tutorial with Examples
- Dart Closures Tutorial with Examples
- Dart methods Tutorial and Examples
- Dart Properties Tutorial and Examples
- Dart dot dot ( .. ) operator
- Dart programming with DartPad online tool
- Install Dart SDK on Windows
- Install Visual Studio Code on Windows
- Install Dart Code Extension for Visual Studio Code
- Install Dart Plugin for Android Studio
- Run your first Dart example in Visual Studio Code
- Run your first Dart example in Android Studio
- Parsing JSON with dart:convert
- Dart List Tutorial with Examples
- Dart Variables Tutorial with Examples
- Dart Map Tutorial with Examples
- Dart Loops Tutorial with Examples
- Dart dart_json_mapper Tutorial with Examples
- What is Transpiler?
Show More