Dart Booleans
Working with true and false values
✅ What are Dart Booleans?
Booleans in Dart represent logical values that can only be true or false. They are essential for decision-making, conditions, and controlling program flow in your applications.
// Boolean examples
bool isActive = true;
bool isComplete = false;
print(isActive); // Output: true
Boolean Basics
True Value
Represents a positive condition
bool isReady = true;
False Value
Represents a negative condition
bool isFinished = false;
Comparisons
Result from comparing values
bool result = 5 > 3; // true
Conditions
Used in if statements and loops
if (isReady) {
print('Go!');
}
🔹 Boolean Declaration
Different ways to create and use boolean variables:
// Direct assignment
bool isLoggedIn = true;
bool hasPermission = false;
// From comparisons
bool isAdult = age >= 18;
bool isEqual = name == 'John';
// From method calls
bool isEmpty = text.isEmpty;
bool contains = list.contains(item);
print('Logged in: $isLoggedIn');
print('Has permission: $hasPermission');
print('Is adult: $isAdult');
Output:
Has permission: false
Is adult: true
🔹 Boolean Operators
Logical operators to combine and manipulate boolean values:
bool a = true;
bool b = false;
// AND operator (&&)
bool andResult = a && b;
print('$a && $b = $andResult'); // Output: true && false = false
// OR operator (||)
bool orResult = a || b;
print('$a || $b = $orResult'); // Output: true || false = true
// NOT operator (!)
bool notA = !a;
bool notB = !b;
print('!$a = $notA'); // Output: !true = false
print('!$b = $notB'); // Output: !false = true
Output:
true || false = true
!true = false
!false = true
🔹 Boolean in Conditions
Using booleans to control program flow:
bool isWeekend = true;
bool isRaining = false;
int temperature = 25;
// Simple if condition
if (isWeekend) {
print('Time to relax!');
}
// Complex conditions
if (isWeekend && !isRaining && temperature > 20) {
print('Perfect day for a picnic!');
} else if (isWeekend && isRaining) {
print('Good day to stay inside and read.');
} else {
print('Regular day, time to work!');
}
// Ternary operator
String activity = isWeekend ? 'Relax' : 'Work';
print('Today\'s activity: $activity');
Output:
Perfect day for a picnic!
Today's activity: Relax
🔹 Boolean Methods
Common methods that return boolean values:
String text = 'Hello Dart';
List<int> numbers = [1, 2, 3, 4, 5];
// String methods returning bool
print(text.isEmpty); // Output: false
print(text.isNotEmpty); // Output: true
print(text.contains('Dart')); // Output: true
print(text.startsWith('Hello')); // Output: true
print(text.endsWith('Java')); // Output: false
// List methods returning bool
print(numbers.isEmpty); // Output: false
print(numbers.isNotEmpty); // Output: true
print(numbers.contains(3)); // Output: true
// Number comparisons
int age = 25;
print(age.isEven); // Output: false
print(age.isOdd); // Output: true
Output:
true
true
true
false
false
true
true
false
true