Interview frequency: …
Short answer
An extension adds methods or getters to an existing type without modifying the original class or creating a subclass, and calls are resolved by the static type.
Explanation
Extensions are useful for grouping a small conversion or behavior close to the type it works on. They do not add state and do not actually change the class's interface, and since choosing an extension depends on the static type, do not use them to build polymorphism that needs runtime dispatch.
Code example
extension StringParsing on String {
int? toSafeInt() => int.tryParse(this);
}
final count = "42".toSafeInt();Common mistakes
- Expecting an extension to add fields or state to the object.
- Forgetting the effect of the static type when an extension with the same name exists.