Junior
What is an extension in Dart and how is it used?
sobes.tech AI
Answer from AI
Extensions in Dart allow adding functionality to existing classes while preserving encapsulation and without modifying their source code.
They are used for:
- Adding methods and getters/setters.
- Defining new operators.
// Defining an extension for String
extension StringExtensions on String {
String capitalize() {
if (isEmpty) {
return this;
}
return this[0].toUpperCase() + substring(1);
}
}
// Using the extension
void main() {
String greeting = "hello";
print(greeting.capitalize()); // Outputs: Hello
}
Extensions are compiled into static methods, which does not affect performance or increase the application's size. They can be imported and used as needed.