Skip to main content

Overview

If statements allow you to execute code conditionally based on boolean expressions. Dart supports simple if statements, if-else statements, and nested conditionals.

Basic Syntax

The basic structure of an if statement in Dart:
if (condition) {
  // Code executes if condition is TRUE
} else {
  // Code executes if condition is FALSE
}

If-Else Statement

An if-else statement provides two execution paths based on a condition:
int calificacion = 81;

if (calificacion >= 60) {
  print('\nAcredito\n');
} else {
  print('\nNo acredito\n');
}
// Output: Acredito
The condition must evaluate to a boolean value (true or false). Dart does not allow non-boolean values in conditional expressions.

Simple If Statement

You can use an if statement without an else clause when you only need to execute code when a condition is true:
int calificacion = 81;

if (calificacion >= 60 && calificacion <= 80) {
  print('\nAlumno regular\n');
}
Use logical operators like && (AND) and || (OR) to combine multiple conditions in a single if statement.

Nested If Statements

You can nest if statements to handle multiple conditions:
int calificacion = 81;

if (calificacion >= 90) {
  print('Excelente');
} else if (calificacion >= 80) {
  print('Muy bien');
} else if (calificacion >= 70) {
  print('Bien');
} else {
  print('Necesita mejorar');
}
// Output: Muy bien

Complete Example

Here’s a complete example demonstrating different types of if statements:
void main() {
  int calificacion = 81;

  // Type conversion demonstration
  String asd = calificacion.toString();
  int valor = int.parse(asd);
  print(valor);

  // If-else statement
  if (calificacion >= 60) {
    print('\nAcredito\n');
  } else {
    print('\nNo acredito\n');
  }

  // Simple if with compound condition
  if (calificacion >= 60 && calificacion <= 80) {
    print('\nAlumno regular\n');
  }

  // Nested if-else statements
  if (calificacion >= 90) {
    print('Excelente');
  } else if (calificacion >= 80) {
    print('Muy bien');
  } else if (calificacion >= 70) {
    print('Bien');
  } else {
    print('Necesita mejorar');
  }
}

Best Practices

1

Use else-if for readability

Instead of deeply nested if statements, use else if chains for better code readability.
2

Keep conditions simple

Break complex conditions into separate boolean variables with descriptive names.
3

Consider switch statements

For multiple discrete values, consider using switch statements instead of long if-else chains.

Common Operators

OperatorDescriptionExample
==Equal tox == 5
!=Not equal tox != 5
>Greater thanx > 5
<Less thanx < 5
>=Greater than or equalx >= 5
<=Less than or equalx <= 5
&&Logical ANDx > 0 && x < 10
``Logical OR`x < 0x > 10`
!Logical NOT!(x == 5)

Build docs developers (and LLMs) love