Introduction
In this article, we will be learning about the boolean data type. Apart from the basic data types, dart also provides us with the boolean data type, which can take only two types of values true and false. To learn about the other data types, go to this link. Along with the boolean data type, will we also discuss the const keyword in dart with the relevant examples.
Boolean in Dart
As discussed above, bool type variables can take only true or false values. Decision control statements mainly use bool variables. In dart, it cannot take the integers such as 1 or 0 only takes true or false, which are compile-time constants.
Syntax:
bool var1 = true;
Bool var2 = false;
Example: This example shows the declaration and initialization of boolean variables.
Code:
void main() {
bool var1 = true;
bool var2 = false;
print(var1);
print(var2);
}
Output:
true
false
Explanation: Variables ‘var1’ and ‘var2’ are of type boolean so they can only take true or false as their values.
Example: In this example, we will assign values to bool variables using the result of a conditional statement.
Code:
void main() {
int a=100, b=200;
//Assigning the values to bool variables.
bool var1 = a > b;
bool var2 = a < b;
print(var1);
print(var2);
}
Output:
false
true
Explanation: Here we use conditional statements for the initialization of bool variables. The result of a > b is false therefore false is assigned to ‘var1’ and result of a < b is true therefore true is assigned to ‘var2’.
Example: In this example, we use bool variables as conditional statements.
Code:
void main() {
bool getInside = true;
bool notGetInside = false;
//Use of bool in control statements
//Use true in this condition.
if(getInside)
print("I am inside 1st If stat.");
//use false in this condition.
if(notGetInside)
print("I am inside 2nd If stat.");
}
Output:
I am inside 1st If stat.
Explanation: Here we use our bool variables as a conditional statement for ‘if' blocks.
Example: Here we use the bool variable as a flag in our conditional statement.
Code:
void main() {
bool flag = true;
for(int i=1; (i<=10 & flag); i++)
{
print(i);
if(i==5){
//blocking the loop.
flag = false;
}
}
}
Output:
1
2
3
4
5
Explanation: If the flag variable in the for loop becomes false then the for loop will stop working and when the ‘i’ becomes 5 we are turning the flag as false. So, from the next iteration flag's value will be false so the for loop will not work and it will print up to 5 only.





