Back to results for “Dart Language Basics & Syntax”
Flutter › Dart Language Basics & Syntax

What are extension methods in Dart, and how do they let you add new useful functionality directly onto an existing class, including classes you did not originally write yourself, such as Dart's own built in String class?

Intermediate

Answer

An extension method lets you effectively add a brand new method or property directly onto an existing class from outside of that class's own original definition, including built in Dart classes or classes that come from an external third party package that you cannot directly modify yourself, and this is especially useful for adding small, genuinely convenient helper functionality, such as a method that checks whether a String is a validly formatted email address, in a way that reads naturally as if that method had always been a fully native, built in part of that original class all along.
extension StringValidation on String {
  bool get isValidEmail => contains('@') && contains('.');
}

print('test@example.com'.isValidEmail); // true
Real-world example A form validation utility adds an isValidEmail extension method directly onto Dart's built in String class, letting any string throughout the entire codebase be validated with the simple, natural sounding syntax myString.isValidEmail.

Common follow-ups: Can an extension method override an already existing method defined on the original class?;What happens if two separate imported extensions both happen to define a method with the exact same name?