Dart if & else statements
last modified December 27, 2020
Dart if & else statements tutorial shows how to create conditions and branches in Dart.
Dart if & else
The if
statement specifies the conditional execution
of a block. If the expression evaluates to true, the block is executed.
If the else
statement is present and the if statement evaluates
to false, the block following else
is executed.
There can be multiple if/else statements.
Dart if/else examples
The following examples demonstrate conditional execution of blocks with if/else.
void main() { var num = 4; if (num > 0) { print("The number is positive"); } }
In the example we have a simple condition; if the num
variable
is positive, the message "The number is positive" is printed to the console.
Otherwise; nothing is printed.
$ dart if_stm.dart The number is positive
The message is printed since value 4 is positive.
void main() { var num = -4; if (num > 0) { print("The number is positive"); } else { print("The number is negative"); } }
Now we have added the second branch. The else
statement specifies
the block that is executed if the if
condition fails.
$ dart if_else.dart The number is negative
For the -4 value, the "The number is negative" is printed.
import 'dart:math'; void main() { const int MAX = 10; var num = new Random().nextInt(MAX) - 5; if (num > 0) { print("The number is positive"); } else if (num == 0) { print("The number is zero"); } else { print("The number is negative"); } }
In this example, we add additional branch with if else
. We generate
random values between -5 and 4. With the help of the if
&
else
statement we print a message for all three options.
In this tutorial, we have covered conditions in Dart.
List all Dart tutorials.