Dart and Flutter Development
Program Control Flow
Making Decisions in Your Code
So far, our code runs in a straight line, from top to bottom. But what if we want our program to react differently based on certain conditions? This is where control flow comes in. It's like giving your program a brain to make decisions. The most basic way to do this is with an if statement.
An
ifstatement checks if a condition is true. If it is, the code inside its block runs. If not, the program just skips it.
Let's say we're building an app that checks if a user is old enough to vote. We can store their age in a variable and then use an if statement to check it.
void main() {
int userAge = 20;
if (userAge >= 18) {
print("You are old enough to vote.");
}
}
The condition here is userAge >= 18. The >= symbol is a relational operator. It compares two values. Dart has several of these you'll use all the time.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 10 |
!= | Not equal to | x != 10 |
> | Greater than | x > 10 |
< | Less than | x < 10 |
>= | Greater than or equal to | x >= 10 |
<= | Less than or equal to | x <= 10 |
Be careful with == (the comparison operator). It's easy to mix up with = (the assignment operator), which you use to assign a value to a variable. Using one where you need the other is a very common beginner mistake!
But what if the user is younger than 18? Our program doesn't say anything. We can provide an alternative path using else.
void main() {
int userAge = 16;
if (userAge >= 18) {
print("You are old enough to vote.");
} else {
print("Sorry, you are not old enough yet.");
}
}
Now, one of the two print statements will always run. For more complex decisions, you can chain conditions together with else if to check for multiple possibilities.
void main() {
String trafficLight = 'yellow';
if (trafficLight == 'green') {
print('Go!');
} else if (trafficLight == 'yellow') {
print('Slow down.');
} else {
print('Stop!');
}
// Output: Slow down.
}
Repeating Actions with Loops
Imagine you need to display a list of 100 messages in an app. You wouldn't want to write 100 separate print statements. Loops solve this by repeating a block of code as many times as you need.
The for loop is perfect when you know exactly how many times you want to repeat an action. It has three parts inside its parentheses, separated by semicolons: a starting point, a condition to continue, and an action to perform after each cycle.
// This loop will print "Hello" 3 times.
void main() {
for (int i = 0; i < 3; i++) {
print('Hello');
}
}
The other main type of loop is the while loop. It's used when you don't know how many times you need to loop, but you know the condition that should stop it. The code inside a while loop will run as long as its condition remains true.
Think of it like this: a
forloop is for running a specific number of laps. Awhileloop is for running until you get tired.
void main() {
int countdown = 3;
while (countdown > 0) {
print(countdown);
countdown = countdown - 1; // Or countdown--;
}
print('Blast off!');
}
// Output:
// 3
// 2
// 1
// Blast off!
A word of caution: if the condition in a while loop never becomes false, you'll create an infinite loop, which will crash your program. Always make sure something inside the loop changes to eventually stop it.
A Cleaner Way for Multiple Choices
Remember our traffic light example? When you have a series of if-else if statements checking the same variable against different values, your code can get long. Dart provides a cleaner alternative called a switch statement for exactly this situation.
void main() {
String userRole = 'admin';
switch (userRole) {
case 'admin':
print('Welcome, administrator!');
break;
case 'editor':
print('You can edit content.');
break;
case 'guest':
print('Welcome! Please log in.');
break;
default:
print('Unknown user role.');
}
}
The switch statement checks the value of userRole. It then jumps to the case that matches. The break keyword is crucial; it tells the program to exit the switch block. Without it, the code would "fall through" and execute the next case as well, which is rarely what you want. The default case is a fallback that runs if no other case matches.
Mastering if, else, switch, and loops is a huge step. You can now control the logical flow of your app, making it respond to different situations and handle repetitive tasks with ease. This is the core logic that powers interactive features in any application you'll build.