OOP & SOLIDEasy20 XP3 min read
What are extension methods in Dart and when should you use them?
TL;DR: Extension methods add functionality to existing types without subclassing. 'extension StringX on String { bool get isEmail => contains('@'); }' lets you call 'email'.isEmail on any String. Ideal for adding domain-specific helpers to SDK types.
Full Answer
Extension methods let you add new methods to any type — including SDK types like String, List, DateTime — without modifying the original class or creating a subclass.
When to use
- ▸Adding validators to String (isEmail, isPhoneNumber, isNumeric)
- ▸Adding formatting helpers to DateTime (timeAgo, toReadable)
- ▸Adding widget utilities to BuildContext (context.theme, context.push())
- ▸Adding null-safety helpers to nullable types
⚠️
Extension methods are resolved statically at compile time, not dynamically. If you store a String as Object, the extension methods won't be accessible.
Code Examples
dartPractical extension methods
Output
true Hello 3h ago
Common Mistakes
- ✗Adding too many extensions to the same type — creates naming conflicts and pollutes autocomplete
- ✗Using extensions when a standalone function would be clearer
Interview Tip
💡
The BuildContext extension is widely used in production Flutter apps. Showing context.push() or context.theme demonstrates practical fluency.
#extension-methods#dart#utility#syntax-sugar