Junior
What are extensions in Dart used for?
sobes.tech AI
Answer from AI
Extensions in Dart allow adding functionality to existing classes without modifying their source code. This is useful for:
- Adding utility methods to standard data types (
String,int,List, etc.). - Extending classes from third-party libraries without modifying them.
- Improving code readability and organizing logic related to a specific type.
Example:
extension StringUtils on String {
String capitalize() {
if (isEmpty) return this;
return this[0].toUpperCase() + substring(1);
}
}
void main() {
String text = "привет мир";
print(text.capitalize()); // Outputs: Привет мир
}