Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn if Statement in Dart | Conditional Statements
Introduction to Dart

book
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

javascript
if (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

dart

main

copy
void main() {
var num=5;
if (num>0) { // 5 > 0 ?
print("number is positive"); // Print if it's `true`
}
}
123456
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

dart

main

copy
void main() {
var num = 10;
if (num.isNegative) { // 10 < 0 ?
print("number < 0"); // Print if it's `true`
}
}
123456
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.

question mark

Choose the correct condition to check if the number is positive. If it is, the program should print "A number greater than zero".

void main() {
int number = 5;
if (___) {
print("A number greater than zero");
}
}

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 1

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

We use cookies to make your experience better!
some-alt