thumbnail

If Else Control Flow statement in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

If else is one of the control flow statements in Dart.

How to use If Else Statements In Dart

If else statements are control flow statements used for controlling the flow of the program based on various conditions.

All conditions provided in an if else program must be boolean values.

If statement with only one condition

main(List<String> args) {
  var number = 4;
  if (number % 2 == 0) {
    print('number ${number} is even');
  }
}

Above program produces following output:

number 4 is even

If else statement with only one condition

main(List<String> args) {
  var number = 3;
  if (number % 2 == 0) {
    print('number ${number} is even');
  } else {
    print('number ${number} is odd');
  }
}

Above program produces following output:

number 3 is odd

If else ladder that checks multiple conditions

This pattern of checking various conditions is also known as if else ladder.

String getFruitName() {
  return 'banana';
}

main(List<String> args) {
  if (getFruitName() == 'apple') {
    print('Fruit is apple');
  } else if (getFruitName() == 'banana') {
    print('Fruit is banana');
  } else {
    print('unknown fruit');
  }
}

Above program produces following output:

Fruit is banana