Switch Case

suggest change

Dart has a switch case which can be used instead of long if-else statements:

var command = 'OPEN';

switch (command) {
  case 'CLOSED':
    executeClosed();
    break;
  case 'OPEN':
    executeOpen();
    break;
  case 'APPROVED':
    executeApproved();
    break;
  case 'UNSURE':
    // An empty case falls through to the next case, here `default`.
  default:
    executeUnknown();
}

A case compares the switched value with a constant, such as an int, a string, or another compile-time constant. Dart 3 also allows pattern cases, so a switch is not limited to those constants.

Empty cases fall through. A non-empty case does not, and break is optional. Before Dart 3, a non-empty case had to end with break, continue, throw, or return; otherwise the program was rejected or failed at runtime.

var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    // Does not fall through. `break` is optional.

  case 'CLOSED': // Empty case falls through.
  case 'LOCKED':
    executeClosed();
    break;
}

Dart 3 removed continue to a switch label. To run the same work from more than one case, call it directly:

var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    executeClosed();
    break;
  case 'LOCKED':
    executeClosed();
    break;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents