Dart if Statement
The Dart if statement executes code based on condition( Boolean expression). This is a branching statement and is used to make decisions in the code based on conditions. Dart if statement allows you to execute a code statement or group of code statements conditionally based on given condition(s). A group of code statements is also called a code block enclosed within { }.
Dart if Statement
The general syntax of the Dart if statement is as follows:
if (condition) { // code to be executed when the condition is true }
The code block will execute when the given condition(s) evaluates to true. The given condition either evaluates to true or false and the decision is made based on the Boolean value of the condition. We can use the if statement in the code when we have a scenario where we want to execute a block of code when it satisfies the given condition or conditions.
Note that we can combine several conditions using conditional operators.
The given if condition will evaluate to be either true or false. If the condition evaluates to true then the code statement(s) inside the if body is executed, if it evaluates to false then the statement outside the if block is executed.
Example
Here’s an example to demonstrate how to use the if statement in Dart:
/* * if Statement demo Dart Program * Dart Tutorials - www.TestingDocs.com */ void main() { int a = 9; // Dart if Statement if (a > 7) { print('Control inside if block'); print('a is greater than 7'); } print('Control after the if'); }
In this example, the condition a > 7 is evaluated. If the condition is true, the code block inside the if statement (the print statements) is executed. Otherwise, if the condition is false, the code block is skipped, and the program continues executing the statement after the if block.
Output
Control inside if block
a is greater than 7
Control after the if
if-else Statement
We can also include an else statement to specify a block of code that should be executed when the condition is false.
/* * if-else Statement demo Dart Program * Dart Tutorials - www.TestingDocs.com */ void main() { int a = 5; // Dart if-else Statement if (a > 7) { print('Control inside if block'); print('a is greater than 7'); } else { print('Control inside else block'); print('a is less than or equal to 7'); } print('Control after the if-else'); }
Output
Control inside else block
a is less than or equal to 7
Control after the if-else
In this example, we have assigned 5 to the variable a. The condition in the if statement a > 7 would be false. Since condition a > 7 is false, the code block inside the else statement is executed.
—
More information on Dart programming language: