tezvyn:

Extension Methods: Add to Classes You Don't Own

AI-drafted, machine-checkedSource: dart.devadvanced

Extension methods let you add functionality to existing classes you don't control. Use them to create fluent APIs, like calling `'42'.parseInt()` instead of `int.parse('42')`.

WHY IT EXISTS Sometimes you're using a class from a library you don't control—like Dart's built-in String class or a class from a third-party package—and wish it had a specific helper method. Since you can't modify the original source code, extension methods provide a way to "add" new methods to the class from your own code.

THE MENTAL MODEL Think of an extension method as adding your own tool to someone else's sealed toolbox. You aren't changing the toolbox itself, but you're making your tool available whenever you're working with it. They are essentially syntactic sugar for static helper functions, making code more readable and object-oriented.

HOW IT WORKS You define an extension on a specific type. The compiler then allows you to call the extension's methods on instances of that type as if they were regular instance methods. For example, extension NumberParsing on String { ... } lets you define new methods that can be called on any string. When you call '42'.parseInt(), the compiler first checks if the String class has a parseInt method. If not, it looks for an imported extension on String that provides it.

WHEN TO USE IT Use extensions to add utility or convenience methods to existing classes. They are perfect for creating fluent, chainable APIs or simplifying common operations. For instance, adding formatting helpers to DateTime or validation logic to String are common use cases.

WHEN NOT TO USE IT Avoid extensions if you can modify the class directly; adding a method to the class is always better. The biggest footgun is that extensions are resolved statically at compile time. This means they cannot be called on variables of type dynamic. Furthermore, if an extension method has the same name as a real instance method, the instance method always wins, which can lead to confusing behavior or silent bugs if the original class is updated later.

ONE CANONICAL EXAMPLE Instead of writing int.parse('42'), you can create an extension to make the code more fluent. First, define the extension:

extension NumberParsing on String { int parseInt() { return int.parse(this); } }

Then you can use it directly on a string variable:

var myNumber = '42'.parseInt(); // myNumber is now the integer 42

Read the original → dart.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.