Mxo.

Back to Blog
Flutter
Dart

Dart's Extension Method

Learn how to use Dart's extension methods to add functionality to existing classes without modifying them.

Mxo MasukuFebruary 6, 20252 min read

Today I learnt about dart's extension method which you can use to extend any class, (even custom classes) to prevent writing lots of boilerplate code.

to be fair, i don't see myself really writing any custom extension methods anytime soon but i thought it would be nice to have my own in-house point of reference.

If you are here and you are not me (well because i read my notes everytime when I feel the urge to doomscroll),

this video offers a better visual lesson that this note ever will.

Working with an extension method would look something like this

extension Name on Class {

bool get isName {

return something

}
}

How you would use this depends on the use case. but before we go there, here is a simpler real world example of where this might work, for email validation:

extension EmailValidation on String {
bool get isEmail {
   final regex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
   return regex.hasMatch(this)
}
}

Then use it like this:

import your helper uptop

final isValid = emailInput.isEmail;

TextField(
  decoration: InputDecoration(
    hintText: 'Email',
    focusedBorder: OutlineInputBorder(
      borderSide: BorderSide(
        color: emailInput.isEmail ? Colors.green : Colors.red,
      ),
    ),
  ),
);

This line:

color: emailInput.isEmail ? Colors.green : Colors.red,

Saves us from doing this each time we want to check an input:

final isValid = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(emailInput);

TextField(
decoration: InputDecoration(
hintText: 'Email',
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$')
.hasMatch(emailInput)
? Colors.green
: Colors.red,
),
),
),
);