Start Coding

Topics

Dart If-Else Statements

If-else statements are fundamental control structures in Dart programming. They allow developers to create conditional logic, enabling programs to make decisions based on specific criteria.

Basic Syntax

The basic structure of an if-else statement in Dart is as follows:


if (condition) {
  // Code to execute if condition is true
} else {
  // Code to execute if condition is false
}
    

The condition is an expression that evaluates to either true or false. If it's true, the code block immediately following the if statement executes. Otherwise, the code in the else block runs.

Simple Example

Here's a straightforward example demonstrating the use of an if-else statement:


int age = 18;

if (age >= 18) {
  print('You are an adult.');
} else {
  print('You are a minor.');
}
    

In this case, the program checks if the age is 18 or older and prints the appropriate message.

Multiple Conditions with Else If

For more complex decision-making, you can use else if to check multiple conditions:


int score = 75;

if (score >= 90) {
  print('A grade');
} else if (score >= 80) {
  print('B grade');
} else if (score >= 70) {
  print('C grade');
} else {
  print('Failed');
}
    

This structure allows for multiple conditions to be checked in sequence, executing the code block of the first true condition encountered.

Nested If-Else Statements

You can also nest if-else statements within each other for more complex logic:


bool isWeekend = true;
bool isRaining = false;

if (isWeekend) {
  if (isRaining) {
    print('Stay home and watch a movie.');
  } else {
    print('Go out and enjoy the day!');
  }
} else {
  print('It\'s a workday.');
}
    

Best Practices

  • Keep conditions simple and readable.
  • Use Dart Switch Statements for multiple conditions on a single variable.
  • Consider using ternary operators for simple, one-line conditions.
  • Avoid deeply nested if-else statements to maintain code clarity.

Related Concepts

To further enhance your understanding of control flow in Dart, explore these related topics:

Mastering if-else statements is crucial for creating dynamic and responsive Dart applications. They form the backbone of decision-making in your code, allowing for flexible and intelligent program behavior.