
Flutter Basics: Conditions and Switch Statements (Quick Reference)
In Dart (and most programming languages), conditional logic controls what happens when. Whether you’re checking values or switching between states, these tools help make decisions in your app. So we use them in checks and validations and make other cool stuff happen. Its like you are programming the brain of your applications using these.
if
, else if
, else
Use if
to test a condition. Add else if
and else
for branching logic. So lets say i want to mark a users grade. If he scores above or equal to 90 he gets a grade of A, less than 90 but greater than or equal 75 its grade B else grade C. This is how you will code it in any language.
int score = 85;
if (score >= 90) {
print("Grade: A");
} else if (score >= 75) {
print("Grade: B");
} else {
print("Grade: C or below");
}
So you can combine multiple conditions by using logical operators and i want to check if a user is an admin and also the owner. I can do it as below.
if (age > 18 && hasID) {
print("Access granted");
}
if (user == "admin" || user == "owner") {
print("Welcome, privileged user");
}
Operator | Meaning | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | x != y |
> | Greater than | score > 70 |
< | Less than | age < 18 |
>= | Greater than or equal | value >= 100 |
<= | Less than or equal | items <= 5 |
&& | Logical AND | a > 0 && b < 10 |
! | Logical NOT | !isLoggedIn |
% | Modulo (remainder) | 7 % 3 // returns 1 |
Compact if-else. This is a short hand way of checking conditions. So you mention the condition then ? symbol followed by what happens if its true or false separated by a : symbol.
String status = (isOnline) ? "Online" : "Offline";
Nested ternary (use carefully). So you can actually go nuts with the Compact if else by nesting it but best to avoid this and only use it for small logic. Always remember that code is best if you can easily read. No point making it cool if its looking back at it after 1 year and you yourself can’t figure what you did.
String grade = (score >= 90)
? "A"
: (score >= 75)
? "B"
: "C";
switch
StatementGreat for checking a value against multiple cases.
String role = "admin";
switch (role) {
case "admin":
print("You have full access");
break;
case "user":
print("Limited access");
break;
default:
print("Unknown role");
}
So just a summary on when to use what
Structure | Use When… |
---|---|
if | You want to test a condition |
else if | Multiple branches of logic |
else | Fallback when no condition is met |
switch | Checking a single value against cases |
Ternary ? : | You want concise conditional assignment |
0 Comments
Be the first to comment