It’s a fact that “Nothing is perfect”
So it is not necessary that all your requirement will be fulfilled with the built-in data types and their functions. That’s the point when the extension methods come into the pool.
What are Extension Methods?
Extension methods extend the capabilities of pre-existing libraries. You may be using extension methods without even realizing it. When you use code completion in an IDE, it will propose extension methods in addition to standard methods.
e.g. parse(), toString(), replace(), isEmpty(), isNotEmpty(), etc.
How can we develop our own Extension Methods?
Let’s start with a simple example.
Assume, I want to develop an extension for String by which I can convert a name into greetings.
e.g. “Salman”.greetings() similar to other built-in string like toString()
We use the extension keyword for our custom extensions same as the class and give a name to our extensions like Greeting and mention the type we want to add to our extension.
Now we will define our extensions method into our Greeting extension same as functions.
this keyword refers to the string value on which we will use this extension method.
Hurray! your extension is ready. Use it where you want.
You can create as much as extension methods as you want with all the built-in libraries like Widget, DateTime, String, List, Map, etc.
If you want to learn it in detail with different libraries then check out my complete video tutorial.
Hope you have enjoyed it!
Thanks for reading!
Keep supporting and don’t forget to applaud 👏 on the article if it helps you.
Md Salman Shaikh is creating YouTube videos & writes blogs related to programming skills
Hey! I know you enjoyed my content. You can buy me a coffee!
Other Famous Articles:
Render Dynamic Flutter Widgets Using JSON
Sometimes we observe the UI or feature changes in the applications like Facebook, Instagram, Whatsapp, etc. without…
Automate your Flutter code with Github Copilot
Are you tired to do thousands of lines of code daily? Do you want a robot who can code on your behalf? Do you know…