Dart Logical Operators


Logical operators in Dart are used to perform logical operations on boolean values. These operators are essential for combining conditional statements and controlling the flow of the program based on multiple conditions. Dart supports three main logical operators:

Overview of Logical Operators

  1. Logical AND (&&)
  2. Logical OR (||)
  3. Logical NOT (!)

1. Logical AND (&&)

  • Description: The logical AND operator returns true if both operands are true; otherwise, it returns false.
  • Usage: Often used to combine multiple conditions in control flow statements like if.

Example:

void main() { bool a = true; bool b = false; // Using logical AND print('a AND b: ${a && b}'); // Output: false print('a AND true: ${a && true}'); // Output: true }

2. Logical OR (||)

  • Description: The logical OR operator returns true if at least one of the operands is true; otherwise, it returns false.
  • Usage: Useful for combining conditions where at least one needs to be true.

Example:

void main() { bool a = true; bool b = false; // Using logical OR print('a OR b: ${a || b}'); // Output: true print('false OR false: ${false || false}'); // Output: false }

3. Logical NOT (!)

  • Description: The logical NOT operator negates the boolean value of its operand. If the operand is true, it returns false, and vice versa.
  • Usage: Used to reverse the boolean value of a single condition.

Example:

void main() { bool a = true; // Using logical NOT print('NOT a: ${!a}'); // Output: false print('NOT false: ${!false}'); // Output: true }

Combining Logical Operators

Logical operators can be combined to create complex conditional expressions. Here’s an example:

Example:

void main() { int age = 20; bool hasLicense = true; if (age >= 18 && hasLicense) { print('You can drive legally.'); } else { print('You cannot drive legally.'); } }

In this example, the program checks if the person is at least 18 years old and has a valid driver's license.

Truth Table for Logical Operators

| A | B | A && B | A || B | !A | |-------|-------|--------|--------|-------| | true | true | true | true | false | | true | false | false | true | false | | false | true | false | true | true | | false | false | false | false | true |

Summary of Logical Operators

OperatorDescriptionExample
&&Logical ANDtrue && false (results in false)
``
!Logical NOT!true (results in false)

Conclusion

Logical operators are fundamental in Dart for creating complex conditions and controlling the program flow. They allow developers to make decisions based on multiple criteria, leading to more dynamic and flexible code. Understanding how to use logical operators effectively is essential for writing efficient Dart applications.