What are Extension Methods?
Extension methods allow you to add new functionality to existing libraries and types without creating a subclass or modifying the original source. This is especially useful when you want to enhance built‑in types like String, List, or int with your own utility methods. Extensions were introduced in Dart 2.7 and have become a powerful tool for making code more expressive and reusable.
Basic Syntax
An extension is declared with the extension keyword followed by a name and the on clause specifying the type being extended. Inside the extension body, you define methods (and optionally getters, setters, operators).
Extension with Generics
You can define extensions on generic types, which is very useful for collections. The type parameter is declared after the extension name.
Adding Getters and Setters
Extensions can also define getters and setters, making them feel like native properties.
Extension Operators
You can define operators inside extensions, enabling custom behavior with existing operators.
Static Methods and Fields
Extensions cannot have static fields, but they can have static helper methods. However, static members are not accessed via the extended instance; they are called on the extension name itself.
Conflicts and Resolution
If multiple extensions define the same method name for the same type, Dart uses the closest import or the one explicitly specified. You can also qualify the extension to resolve ambiguity.
Extending Nullable Types
You can also write extensions on nullable types (using ?). This allows you to call methods safely on potentially null values.
Key Takeaways
- Extensions add new functionality to existing types without subclassing.
- Use
extension Name on Typesyntax.
- Use
- Extensions can define methods, getters, setters, and operators.
- Generic extensions work with collection types.
- Extensions can be qualified to resolve naming conflicts.
- They are a great way to keep code clean and expressive.