Switch and case
Switch statements in Dart compare integer, string, or compile-timeconstants using ==. The compared objects must all be instances of thesame class (and not of any of its subtypes), and the class must notoverride ==.Enumerated types work well in switch statements.
Note: Switch statements in Dart are intended for limited circumstances, such as in interpreters or scanners.
Each non-empty case clause ends with a break statement, as a rule.Other valid ways to end a non-empty case clause are a continue,throw, or return statement.
Use a default clause to execute code when no case clause matches:
var command = 'OPEN';switch (command) {case 'CLOSED':executeClosed();break;case 'PENDING':executePending();break;case 'APPROVED':executeApproved();break;case 'DENIED':executeDenied();break;case 'OPEN':executeOpen();break;default:executeUnknown();}
The following example omits the break statement in a case clause,thus generating an error:
var command = 'OPEN';switch (command) {case 'OPEN':executeOpen();// ERROR: Missing breakcase 'CLOSED':executeClosed();break;}
However, Dart does support empty case clauses, allowing a form offall-through:
var command = 'CLOSED';switch (command) {case 'CLOSED': // Empty case falls through.case 'NOW_CLOSED':// Runs for both CLOSED and NOW_CLOSED.executeNowClosed();break;}
If you really want fall-through, you can use a continue statement anda label:
var command = 'CLOSED';switch (command) {case 'CLOSED':executeClosed();continue nowClosed;// Continues executing at the nowClosed label.nowClosed:case 'NOW_CLOSED':// Runs for both CLOSED and NOW_CLOSED.executeNowClosed();break;}
A case clause can have local variables, which are visible only insidethe scope of that clause.