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-Else Statement

An if-else statement provides two execution paths based on a condition:
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:
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:

Complete Example

Here’s a complete example demonstrating different types of if statements:

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