Extension methods in Dart is a life saver.

Hello dev, have you ever thought about having a specific method to solve a problem on your project, and the library you are using or even the Dart language, does not have it… Yeah, if you didn’t pass through this situation, you will pass for sure. That’s why I decided to talk about the Extension methods, and believe me it saved my life a bunch of times.

To contextualise, let’s first see how the Extension methods works because if you have never used before, maybe you don’t know anything related to that. Ok, basically the structure of this thing is like the image bellow.

We have this reserved word “extension” for declare one Extension methods the same thing you do when you want to declare a function. After that you have to give it a name, until here pretty much the same behaviour as a normal function, and tell in which type you want to apply.

Now inside the curly braces you can create as many functions you want, but wait, now it looks like a class right now because we are going to have functions inside of it. Hm… Lets create a real example, because maybe I created a mess in your head, and write code is a good way to learn.

For that I’ll use the DartPad, and by the way it’s a really good tool to study Dart, so now according to this image bellow I’ll try to explain whats going on.

In this example I wanted to capitalize my name, and for that I created this extension with the name “StringExtension”, to be executed in the String type. Inside that I have this function called “capitalize” with a return type String, until here all good right?

Now comes my logic part, and in this part I’m just separating the words in the phrase by the blank space, and in each word I’ll be able to change the first letter to upper case and after that join everything together again.

See, it was not that difficult… and you can call this “capitalize” extension in every String in your code, like you are used to do when you call for example .toInt().

That is it, I will tell why I think Extension methods is a life saver in my point of view. First benefit of using it is make the code clearer and with a single porpuse, because you are going to have different functionalities to extend in one specific type. Second benefit is, add a feature to a existing package or even to the Dart language. And last but not least, call your function in an elegant and clean way.

And if you think that all these things that I said before is not enough, go ahead and read more about Extension methods and try to use in your projects to see if is good for you.

A simple Flutter dev learning everyday.