Dart Booleans
Dart Booleans
Very often in programming, you need a value that can only be one of two things, like:
- YES or NO
- ON or OFF
- TRUE or FALSE
For this, Dart has the bool type.
A bool value is either true or false:
Example
void main() {
bool isDartFun = true;
bool isFishTasty = false;
print(isDartFun);
print(isFishTasty);
}
Try it Yourself »
Result:
true
false
A value of type bool is called a boolean.
Boolean Expressions
A comparison, like "is 10 greater than 9?", gives a boolean as its answer.
This kind of code is called a boolean expression:
Result:
true
false
true
You can compare variables, and you can store the answer in a variable:
Example
void main() {
int myAge = 25;
int votingAge = 18;
bool canVote = myAge >= votingAge;
print(canVote);
}
Try it Yourself »
Result:
true
Strings can also be compared with ==:
Example
void main() {
var password = 'secret';
print(password == 'secret');
print(password == 'Secret');
}
Try it Yourself »
Result:
true
false
Learn all comparison operators in the Comparison chapter.
The NOT Operator
The ! operator turns true into false, and false into true:
Result:
false
true
You can also join booleans with && (and) and || (or), which you will learn in the Logical chapter.
Booleans in Conditions
Booleans are the base of all decisions in a program.
The if statement runs a block of code only when a boolean is true:
Example
void main() {
int temperature = 30;
if (temperature > 25) {
print('It is a hot day');
} else {
print('It is not so hot');
}
}
Try it Yourself »
Result:
It is a hot day
You will learn more about if in the If...Else chapter.
Only true and false
In some languages, values like 1, 0 or an empty string count as true or false.
Dart does not do this.
A condition must be a real bool, so this program does not run:
Result:
main.dart:3:7: Error: A value of type 'int' can't be assigned to a variable of type 'bool'.
if (count) {
^
Write a comparison instead, so the condition is a boolean:
Example
void main() {
int count = 1;
if (count != 0) {
print('Count is not zero');
}
}
Try it Yourself »
Result:
Count is not zero
Tip: To turn the text 'true' or 'false' into a boolean, use bool.parse().
Read more in the Type Conversion chapter.