Control Flow in Dart: If, Switch, and Loops Made Simple

Control flow in programming helps you decide what your code does based on certain conditions. In Dart, the main tools for control flow are if statements, switch statements, and loops. Let’s break these down simply.

1. If Statements

An if statement allows your code to make decisions. It checks a condition, and if that condition is true, it runs a block of code.

Example

  • If a person’s age is 18 or older, print “You can vote.”
  • Else, print “You cannot vote.”

This helps your program respond differently based on age.

2. Switch Statements

A switch statement is useful when you have multiple options based on one variable. It checks a variable against different cases.

Example

  • If the day is "Monday," print “Start of the week!”
  • If it’s "Friday," print “Weekend is near!”

Using switch keeps your code clean and easy to read.

3. Loops

Loops let you repeat code multiple times. The main types are:

For Loop

Use a for loop when you know how many times to repeat.

  • Example: Print numbers from 1 to 5.

While Loop

A while loop continues as long as a condition is true.

  • Example: Keep asking for user input until they provide the correct answer.

Do-While Loop

This loop is similar to the while loop, but it runs at least once.

  • Example: Show a menu and ask for a choice, ensuring the menu displays first.

Conclusion

Control flow helps your Dart programs make decisions and repeat actions. Once you start practicing, these concepts will become much clearer. Keep experimenting, and you’ll master control flow in no time!


NEXT TOPIC