Kursinhalt
Introduction to Dart
Introduction to Dart
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
The syntax of the conditional operator is so simple: if
keyword, condition in the parentheses ( )
and a code block in the curly brackets { }
.
The opening curly bracket { }
marks the beginning of a code block, and the closing curly bracket indicates its end.
Example 1
main
void 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
void 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!