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:
1. var command = 'OPEN';
2. switch (command) {
3. case 'CLOSED':
4. executeClosed();
5. break;
6. case 'PENDING':
7. executePending();
8. break;
9. case 'APPROVED':
10. executeApproved();
11. break;
12. case 'DENIED':
13. executeDenied();
14. break;
15. case 'OPEN':
16. executeOpen();
17. break;
18. default:
19. executeUnknown();
20. }
The following example omits the break statement in a case clause,thus generating an error:
1. var command = 'OPEN';
2. switch (command) {
3. case 'OPEN':
4. executeOpen();
5. // ERROR: Missing break
7. case 'CLOSED':
8. executeClosed();
9. break;
10. }
However, Dart does support empty case clauses, allowing a form offall-through:
1. var command = 'CLOSED';
2. switch (command) {
3. case 'CLOSED': // Empty case falls through.
4. case 'NOW_CLOSED':
5. // Runs for both CLOSED and NOW_CLOSED.
6. executeNowClosed();
7. break;
8. }
If you really want fall-through, you can use a continue statement anda label:
1. var command = 'CLOSED';
2. switch (command) {
3. case 'CLOSED':
4. executeClosed();
5. continue nowClosed;
6. // Continues executing at the nowClosed label.
8. nowClosed:
9. case 'NOW_CLOSED':
10. // Runs for both CLOSED and NOW_CLOSED.
11. executeNowClosed();
12. break;
13. }
A case clause can have local variables, which are visible only insidethe scope of that clause.
