MOCKSTACKS
EN
Questions And Answers

More Tutorials









Dart Switch Case


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':
 // missing break statement means this case will fall through
 // to the next statement, in this case the default case
 default:
 executeUnknown();
}

You can only compare integer, string, or compile-time constants. The compared objects must be instances of the same class (and not of any of its subtypes), and the class must not override ==.
One surprising aspect of switch in Dart is that non-empty case clauses must end with break, or less commonly, continue, throw, or return. That is, non-empty case clauses cannot fall through. You must explicitly end a non-empty case clause, usually with a break. You will get a static warning if you omit break, continue, throw, or return, and the code will error at that location at
runtime.

var command = 'OPEN';
switch (command) {
 case 'OPEN':
 executeOpen();
 // ERROR: Missing break causes an exception to be thrown!!
 case 'CLOSED': // Empty case falls through
 case 'LOCKED':
 executeClosed();
 break;
}

If you want fall-through in a non-empty case, you can use continue and a label:

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



Conclusion

In this page (written and validated by ) you learned about Dart Switch Case . What's Next? If you are interested in completing Dart tutorial, your next topic will be learning about: Dart Converting Data.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.