if Statement in Dart
if Statement
An if
statement is a construct that allows you to execute a code block if a specific condition is met.
The condition is an expression that evaluates to a bool
value, which can be true
or false
. If the condition is true
, the block of code is executed. If the condition is false
, the block of code is skipped.
Syntax
javascript9123if (condition) {// Code block};
The syntax of the conditional operator is simple: the if
keyword, a condition inside the opening parenthesis (
and closing parenthesis )
, and a code block inside the opening curly bracket {
and closing curly bracket }
.
The opening curly bracket {
marks the beginning of a code block, and the closing curly bracket }
indicates its end.
Example 1
main
123456void main() { var num=5; if (num>0) { // 5 > 0 ? print("number is positive"); // Print if it's `true` } }
This program demonstrates an if
statement by declaring a variable num with a value of 5
and checking if num is greater than 0
. Since the condition num > 0
is true
, the code block inside the if statement executes, printing "number is positive" to the console.
Example 2
main
123456void main() { var num = 10; if (num.isNegative) { // 10 < 0 ? print("number < 0"); // Print if it's `true` } }
This code checks if the number is negative using the isNegative
method. If the number is less than zero, it prints "number < 0"
, but since the value of num
is 10
, which is not negative, the condition is not met and nothing is printed.
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen