What is "default" in Dart?

Thu, Dec 22, 2022

Read in 2 minutes

In this post we take a look at "default" keyword with some example codes.

In Dart, default is a keyword that is used in conjunction with the switch statement to specify a default case to be executed if none of the other cases match.

The switch statement in Dart allows you to test a variable against a series of values and execute different code depending on which value matches. The general syntax of a switch statement is as follows:

switch (variable) {
  case value1:
    // code to execute if variable equals value1
    break;
  case value2:
    // code to execute if variable equals value2
    break;
  // more cases
  default:
    // code to execute if variable does not match any of the cases
    break;
}

In this syntax, the default case is optional and is used to specify code to be executed if none of the other cases match the value of the variable. The default case is always listed last in the switch statement.

Here is an example to illustrate the use of default:

void main() {
  var fruit = 'apple';
  switch (fruit) {
    case 'banana':
      print('You chose a banana.');
      break;
    case 'orange':
      print('You chose an orange.');
      break;
    default:
      print('You chose something else.');
      break;
  }
}

In this example, the switch statement tests the value of the fruit variable against the values 'banana' and 'orange'. If fruit matches one of these values, the corresponding message is printed to the console. If fruit does not match either value, the default case is executed and the message “You chose something else.” is printed.

The output of this code would be:

You chose something else.

In summary, the default keyword in Dart is used in conjunction with the switch statement to specify code to be executed if none of the other cases match the value of the variable being tested. It is an optional case that is always listed last in the switch statement.


Shohruh AK



Category:

Dart

Tags:



See Also

What is "covariant" in Dart?
What is "continue" in Dart?
What is "class" in Dart?
What is "case" in Dart?
What is "break" in Dart?