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?
IntermediateAnswer
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); // trueReal-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.