Popular Searches
Popular Course Categories
Popular Courses

Dart Conditional Statements

Dart Conditional Statements

5 mins Dart Basics

Dart Conditional Statements

Conditional statements are used in Dart to make decisions in a program. They allow a program to execute different blocks of code depending on whether a condition is true or false.

Conditional statements are an important part of Dart programming fundamentals. JustAcademy's Flutter curriculum includes control statements such as if, loops, and switch as part of Dart Programming Fundamentals. :contentReference[oaicite:0]{index=0}

Learn Flutter with JustAcademy: JustAcademy Flutter Training

Register for a demo: JustAcademy Course Demo Registration


1. What Are Conditional Statements?

A conditional statement checks a condition and decides which code should be executed. Conditions generally produce a Boolean value: true or false.

int age = 20;

if (age >= 18) {
  print("You are an adult");
}

In this example, Dart checks whether age >= 18 is true. If it is true, the code inside the if block is executed.

2. Why Are Conditional Statements Important?

Conditional statements are used in almost every application. They can be used to:

  • Validate user input.
  • Check login status.
  • Determine whether a student passed or failed.
  • Calculate discounts.
  • Check age eligibility.
  • Display different messages.
  • Control application features based on user roles.
  • Display different Flutter widgets based on application state.
  • Handle different application states such as loading, success, and error.

3. Types of Conditional Statements in Dart

Statement Purpose
if Executes code when a condition is true.
if-else Chooses between two blocks of code.
else-if Checks multiple conditions.
Nested if Places one conditional statement inside another.
switch Selects a block based on matching values or patterns.
Ternary operator Provides a short expression for choosing between two values.
Null-aware conditional expressions Provides fallback behavior for nullable values.

4. if Statement

The if statement executes a block of code only when its condition evaluates to true.

Syntax

if (condition) {
  // code to execute
}

Example

int age = 25;

if (age >= 18) {
  print("Eligible to vote");
}

Since 25 >= 18 is true, the message is printed.

Another Example

int marks = 80;

if (marks >= 40) {
  print("Student passed");
}

5. if Statement with Multiple Conditions

Logical operators can be used with an if statement to check more than one condition.

int age = 25;
bool hasId = true;

if (age >= 18 && hasId) {
  print("Access allowed");
}

Here, both conditions must be true because the && operator is used.

6. if-else Statement

The if-else statement provides two possible paths. If the condition is true, the if block executes. Otherwise, the else block executes.

Syntax

if (condition) {
  // code when condition is true
} else {
  // code when condition is false
}

Example

int age = 16;

if (age >= 18) {
  print("Adult");
} else {
  print("Minor");
}

Student Result Example

int marks = 35;

if (marks >= 40) {
  print("Pass");
} else {
  print("Fail");
}

7. else-if Statement

The else-if structure is useful when a program needs to check multiple conditions.

Syntax

if (condition1) {
  // code
} else if (condition2) {
  // code
} else if (condition3) {
  // code
} else {
  // default code
}

Example: Student Grades

int marks = 85;

if (marks >= 90) {
  print("Grade A+");
} else if (marks >= 80) {
  print("Grade A");
} else if (marks >= 70) {
  print("Grade B");
} else if (marks >= 60) {
  print("Grade C");
} else if (marks >= 40) {
  print("Grade D");
} else {
  print("Fail");
}

Dart evaluates these conditions from top to bottom. Once a matching condition is found, its block is executed and the remaining branches are skipped.

8. Multiple Conditions Using else-if

int temperature = 35;

if (temperature >= 40) {
  print("Very Hot");
} else if (temperature >= 30) {
  print("Hot");
} else if (temperature >= 20) {
  print("Pleasant");
} else {
  print("Cold");
}

9. Nested if Statements

A nested if statement is an if statement placed inside another if statement.

Example

int age = 25;
bool hasLicense = true;

if (age >= 18) {
  if (hasLicense) {
    print("You can drive");
  }
}

The second condition is checked only after the first condition is satisfied.

Nested if with Login

String email = "[email protected]";
String password = "12345";

if (email.isNotEmpty) {
  if (password.isNotEmpty) {
    print("Login information provided");
  }
}

10. Nested if-else

int age = 22;
bool hasId = true;

if (age >= 18) {
  if (hasId) {
    print("Entry allowed");
  } else {
    print("ID is required");
  }
} else {
  print("You are underage");
}

11. switch Statement

The switch statement is useful when a program needs to select between multiple possible cases based on the value of an expression. JustAcademy's Flutter curriculum specifically includes switch among Dart control statements. :contentReference[oaicite:1]{index=1}

Basic Syntax

switch (expression) {
  case value1:
    // code
    break;

  case value2:
    // code
    break;

  default:
    // default code
}

Example

int day = 2;

switch (day) {
  case 1:
    print("Monday");
    break;

  case 2:
    print("Tuesday");
    break;

  case 3:
    print("Wednesday");
    break;

  default:
    print("Invalid day");
}

12. switch with String Values

A switch can also be used with strings.

String role = "admin";

switch (role) {
  case "admin":
    print("Full access");
    break;

  case "editor":
    print("Edit access");
    break;

  case "user":
    print("Limited access");
    break;

  default:
    print("Unknown role");
}

13. switch for a Menu System

String option = "profile";

switch (option) {
  case "home":
    print("Opening Home");
    break;

  case "profile":
    print("Opening Profile");
    break;

  case "settings":
    print("Opening Settings");
    break;

  case "logout":
    print("Logging out");
    break;

  default:
    print("Invalid option");
}

14. default Case in switch

The default branch provides a fallback when none of the listed cases match.

int number = 10;

switch (number) {
  case 1:
    print("One");
    break;

  case 2:
    print("Two");
    break;

  default:
    print("Another number");
}

15. Modern switch Expressions

Modern Dart also supports switch expressions, which can be used to produce a value directly. This is useful when a program needs to map one value to another.

String getDayName(int day) {
  return switch (day) {
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    4 => "Thursday",
    5 => "Friday",
    6 => "Saturday",
    7 => "Sunday",
    _ => "Invalid day",
  };
}

void main() {
  print(getDayName(2));
}

In this example, _ acts as a default pattern for values that do not match the earlier cases.

16. Ternary Conditional Operator

The ternary operator is a short way to select between two values.

Syntax

condition ? valueIfTrue : valueIfFalse;

Example

int age = 20;

String result = age >= 18 ? "Adult" : "Minor";

print(result);

This is a shorter alternative to a simple if-else assignment.

17. Ternary Operator with Student Results

int marks = 75;

String result = marks >= 40 ? "Pass" : "Fail";

print(result);

18. Ternary Operator in Flutter

Conditional expressions are especially useful when selecting a widget or text based on application state.

bool isLoggedIn = true;

Text(
  isLoggedIn
      ? "Welcome Back!"
      : "Please Login",
)

Another example:

bool isLoading = false;

Widget body = isLoading
    ? CircularProgressIndicator()
    : Text("Data Loaded");

19. Null-Coalescing Operator (??)

The ?? operator provides a fallback value when a nullable expression is null.

String? username;

String displayName = username ?? "Guest";

print(displayName);

If username is null, "Guest" is used.

Example

String? city = null;

String userCity = city ?? "Unknown";

print(userCity);

20. Null-Coalescing Assignment (??=)

The ??= operator assigns a value only when the variable is currently null.

String? name;

name ??= "Guest";

print(name);

If name already has a value, the existing value is preserved.

String? name = "Rahul";

name ??= "Guest";

print(name); // Rahul

21. Conditional Statements with User Authentication

String email = "[email protected]";
String password = "12345";

if (email.isEmpty || password.isEmpty) {
  print("Please enter all required fields");
} else if (password.length < 5) {
  print("Password is too short");
} else {
  print("Login information is valid");
}

22. Conditional Statements for Age Verification

int age = 21;

if (age < 13) {
  print("Child");
} else if (age < 18) {
  print("Teenager");
} else if (age < 60) {
  print("Adult");
} else {
  print("Senior Citizen");
}

23. Conditional Statements for an E-Commerce Discount

double amount = 6000;
double discount;

if (amount >= 5000) {
  discount = amount * 0.20;
} else if (amount >= 3000) {
  discount = amount * 0.10;
} else if (amount >= 1000) {
  discount = amount * 0.05;
} else {
  discount = 0;
}

double finalAmount = amount - discount;

print("Discount: ₹$discount");
print("Final Amount: ₹$finalAmount");

24. Conditional Statements for Student Grades

int marks = 82;

if (marks >= 90) {
  print("Excellent - A+");
} else if (marks >= 80) {
  print("Very Good - A");
} else if (marks >= 70) {
  print("Good - B");
} else if (marks >= 60) {
  print("Average - C");
} else if (marks >= 40) {
  print("Pass - D");
} else {
  print("Fail");
}

25. Conditional Statements with Boolean Values

Boolean variables are frequently used in conditional statements.

bool isLoggedIn = true;

if (isLoggedIn) {
  print("Show Dashboard");
} else {
  print("Show Login Screen");
}

26. Multiple Conditions Using &&

int age = 25;
bool hasTicket = true;

if (age >= 18 && hasTicket) {
  print("Entry allowed");
} else {
  print("Entry denied");
}

27. Multiple Conditions Using ||

bool isAdmin = false;
bool isManager = true;

if (isAdmin || isManager) {
  print("Access granted");
} else {
  print("Access denied");
}

28. Negating a Condition Using !

bool isBlocked = false;

if (!isBlocked) {
  print("User can access the application");
}

29. Conditional Statements in Flutter Application States

Flutter applications frequently need to display different UI depending on the current state of the application. Conditional expressions can help select different widgets.

bool isLoading = true;

if (isLoading) {
  print("Show loading indicator");
} else {
  print("Show application content");
}

A widget-based example:

Widget build(BuildContext context) {
  bool isLoading = false;

  return isLoading
      ? const CircularProgressIndicator()
      : const Text("Content Loaded");
}

30. if-else vs switch

if-else switch
Best for conditions and ranges. Useful for matching alternatives.
Can use complex Boolean expressions. Works well with discrete values and patterns.
Example: marks >= 80 Example: case "admin"
Useful for ranges such as age or marks. Useful for menus, roles, commands, and known alternatives.

31. if-else vs Ternary Operator

if-else Ternary
Useful for larger blocks of logic. Useful for short expressions.
Can contain multiple statements. Returns one of two expressions.
Better for complex logic. Better for simple value selection.

32. Common Mistakes

Mistake 1: Forgetting the Condition

// Incorrect
if {
  print("Hello");
}

Correct:

if (true) {
  print("Hello");
}

Mistake 2: Using = Instead of ==

int age = 18;

if (age == 18) {
  print("Age is 18");
}

= is used for assignment, while == is used for equality comparison.

Mistake 3: Creating Unnecessary Nested Conditions

Instead of:

if (age >= 18) {
  if (hasId) {
    print("Allowed");
  }
}

You can often write:

if (age >= 18 && hasId) {
  print("Allowed");
}

Mistake 4: Using a Complex Ternary Expression

Ternary operators are useful for simple decisions. If the expression becomes difficult to understand, an if-else statement is generally easier to read.

33. Best Practices

  • Keep conditions simple and readable.
  • Use meaningful variable names.
  • Use if-else for complex decision-making logic.
  • Use else-if when checking multiple ranges or conditions.
  • Use switch when matching multiple known alternatives.
  • Use the ternary operator for short value-selection expressions.
  • Use logical operators carefully when combining conditions.
  • Handle nullable values with appropriate null-aware operators.
  • Keep Flutter UI conditions easy to understand.

34. Complete Dart Conditional Statement Example

void main() {
  String username = "Rahul";
  int age = 22;
  double marks = 85;
  bool isLoggedIn = true;

  if (!isLoggedIn) {
    print("Please login first");
    return;
  }

  print("Welcome $username");

  if (age < 18) {
    print("Minor user");
  } else if (age < 60) {
    print("Adult user");
  } else {
    print("Senior user");
  }

  if (marks >= 90) {
    print("Grade A+");
  } else if (marks >= 80) {
    print("Grade A");
  } else if (marks >= 60) {
    print("Grade B");
  } else if (marks >= 40) {
    print("Grade C");
  } else {
    print("Fail");
  }

  String status = marks >= 40 ? "Passed" : "Failed";

  print("Result: $status");
}

35. Quick Revision

Concept Purpose Example
if Execute code when a condition is true if (age >= 18)
if-else Choose between two alternatives if (...) {} else {}
else-if Check multiple conditions else if (marks >= 80)
Nested if Check a condition inside another condition if (...) { if (...) {} }
switch Match alternatives switch (role)
Ternary Short two-way value selection condition ? a : b
?? Provide a fallback for null name ?? "Guest"
??= Assign only when null name ??= "Guest"

36. Practice Exercises

  1. Write a Dart program to check whether a number is positive, negative, or zero.
  2. Write a program to check whether a person is eligible based on age.
  3. Create an if-else program to determine whether a student passed or failed.
  4. Use else-if to calculate student grades.
  5. Create a nested if example for login validation.
  6. Use switch to display the name of a day.
  7. Use switch to implement a simple menu.
  8. Use the ternary operator to display Login or Logout.
  9. Use && to check two conditions together.
  10. Use || to check whether a user is an admin or manager.
  11. Use ?? to provide a default username.
  12. Create a Flutter UI example that displays a loading indicator while data is loading.

37. Key Takeaways

  • Conditional statements allow Dart programs to make decisions.
  • if executes code when a condition is true.
  • if-else provides two possible execution paths.
  • else-if is useful for checking multiple conditions.
  • Nested conditions allow one decision to depend on another.
  • switch is useful for matching multiple alternatives.
  • The ternary operator provides a concise way to choose between two values.
  • ?? provides a fallback value for nullable expressions.
  • Conditional logic is heavily used in Flutter applications to control application behavior and UI.

JustAcademy's Flutter course includes Dart Programming Fundamentals, with control statements such as if, loops, and switch, followed by Flutter UI, navigation, API integration, Firebase, state management, testing, and project work. :contentReference[oaicite:2]{index=2}

38. Learn Flutter with JustAcademy

Explore the complete Flutter training program and continue learning Dart and Flutter through practical coding, assignments, and project-based development.

Visit JustAcademy Flutter Training

Register for JustAcademy Course Demo

whatsapp