Why should we use Extension Methods in Flutter?

Alperen Ekin
HardwareAndro
Published in
3 min readSep 10, 2020

Dart and Flutter are becoming more powerful day by day. If you worked with Kotlin or Swift, probably you are already familiar with term Extension. However extension methods had arrived to Dart with Dart 2.6. They bring new features to your classes however not only for your classes but also the core classes like String. Therefore we can say that extensions make your objects more powerful. Besides that it helps you with your clean code aim and increase code readability.

Let’s See Some Code

Before examples, i really believe that extensions are so useful and there can be limitless of usage for them, so we should be open for new examples always.

Let’s think about what we do when we want to give numerical values about height, width padding etc…

Container (
width : MediaQuery.of(context).size.width * (0.1);
height: MediaQuery.of(context).size.height* (0.1);
)

So such simple operation we use long line of code and for every numerical value we will be keep repeating it.
However by using extensions we can avoid from that problem

extension ContextExtension on BuildContext {
MediaQueryData get mediaQuery => MediaQuery.of(this);
}
extension MediaQueryExtension on BuildContext {
double get height(double value) => mediaQuery.size.height*value;
double get width(double value => mediaQuery.size.width*value;
}

And at the end you can use like:

Container (
width : context.height(0.1);
height: context.width(0.1);
)

If we think about how often it is used in a project, it has a lot advantages and easy to read. However this is only one possible usage.

Let’s imagine a scenario about register or login. Obviously we would like to limit the number of minimum character and by using an extension on string this can be provided easily

extension PasswordExtension on String {  bool get isValidPassword => this.length >= 6;

}

This keyword is quite important here. It refers to object we call the extension method with.

And if we want to check about the password

String myPassword = "examplePassword",
if( myPassword.isvalidPassword ){
// do rest of validation
}

As it is seen , this is such simple and effective way to add new functionality on your string.

If you want to see, more concrete and bigger example, here it is;

extension FutureExtension<T> on Future {
Widget toBuild<T>({Widget Function(T data) onSucces, Widget onError}) {
return FutureBuilder<T>(
future: this,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.active:
case ConnectionState.waiting:
return _centerLoading;
case ConnectionState.done:
if (snapshot.hasData) {
child: onSucces(snapshot.data),
);
} else {
if (onError != null) return onError;
//return error
}

break;
default:
//do something about connection problem
}
},
);
}
}

You can easily this piece of code as base template for FutureBuilder operations. Here this refers our future call again.

someFutureOperation.toBuild(
onSucces: (data) {
return someListViewOperation(data);
},
),

The usage is short and clean! A future operation like a Get request to an API has extra power now. It doesn’t matter how many operations like that you have, the job is done in a few lines and it can be even used in other projects without requiring adjustments.

As a result, extensions enable new functionalities to our code. They are reusable and effective. It is definitely worth to try and exploit the power of extensions.

Special thanks to Veli Bacık for providing me his examples. You can reach the examples from link above.
This is it for today, see you in the next articles.
Stay Healthy 🙋‍♂️

--

--