Don't you love AI...
1. Switch Blocks / Switch Expressions
Purpose
Used for control flow to handle different cases of an expression or variable.
Switch Block (Traditional)
Uses the switch statement with case labels.
Requires explicit break statements (unless using => for shorthand).
Can use default for unmatched cases.
dartCopyEditvoid main() {
String fruit = "apple";
switch (fruit) {
case "apple":
print("It's an apple!");
break;
case "banana":
print("It's a banana!");
break;
default:
print("Unknown fruit.");
}
}
Switch Expressions (Newer, More Concise)
Returns a value directly.
More concise than a traditional switch block.
Can be used inside assignments or expressions.
dartCopyEditString describeFruit(String fruit) => switch (fruit) {
"apple" => "A sweet red fruit",
"banana" => "A long yellow fruit",
_ => "Unknown fruit"
};
void main() {
print(describeFruit("apple")); // A sweet red fruit
}
2. Extensions and Extension Types
Purpose
Used to extend functionality of existing classes without modifying them.
Extensions (Adding Methods to Existing Classes)
Allows adding new methods and properties to existing types.
Does not modify the original class.
dartCopyEditextension StringExtensions on String {
bool get isPalindrome => this == split('').reversed.join('');
}
void main() {
print("racecar".isPalindrome); // true
}
Extension Types (New in Dart 3.3)
A stronger way to define custom wrappers around existing types.
Used for type safety and code clarity.
Restricts direct access to underlying data.
dartCopyEditextension type Email(String value) {
bool get isValid => value.contains('@');
}
void main() {
Email email = Email("test@example.com");
print(email.isValid); // true
}
Key Difference from Extensions:
Extension types create new distinct types (not just added functionality).
Helps enforce stricter type safety.
Summary:
FeaturePurposeSwitch BlockTraditional multi-case control flowSwitch ExpressionMore concise way to return values in switch casesExtensionsAdd methods/properties to existing typesExtension TypesCreate distinct types for better type safety