Using extension-methods in Flutter
I have already switched to Flutter as a Professional Flutter developer and I am loving it but coming from an Android background and been in love with Kotlin language too, indeed missing some of the features from the Kotlin language in Dart.
And one of them is an “extension methods”.
As Dart 2.6 has arrived It has a feature to implement an extension methods something like Kotlin has.
In this article, I am going to explain how we can use “extension methods” in the Flutter app.
Extension Methods
Let’s see what extension methods are and what they do.
In the simple word If I explain it to you then “It will get you rid of from the Utility class with lots of static methods you are creating all along.”
And in a broad term, “Extension methods are methods added to an object after an original object compiled.”
Let’s see the example code of the utility class that we may are using currently.
In the above code, I am converting the first letter of the String
to the uppercase.
Let’s see how extension methods can help us to get rid of this static method.
What we have done here is, Instead of creating a Util class, we have created a extension
named StringExtension
on the String
type and then used this
to get the current instance.
You can also create an extension method for any type like a double
/int
or should I say a num
!
But What about Flutter?
Is it possible to create an “extension methods” for the Widgets?
And the answer is Yes…
Let’s see how…
We are going to create a Text
Widget with some padding
, margin
, and background color
and to do so we will use a Container
Widget as a Parent widget of Text
.
And the code will look like this:
Now let’s try creating this Text
with extension methods.
For that, we are going to create an extension
named ExtendedText
on Widget
type and the code will look like below and it will work the same as our normal code.
And now you can wrap your Text
widget with Container
with a single line of Code only that will make your code more readable.
Note: In Flutter extension methods are available from it’s latest stable release, i.e 1.12.13+hotfix.5
That’s it for now, We can discuss “extension methods” in-depth in another article.
To Know more about the extension-methods
in Dart check out below Article by Lasse Reichstein Holst Nielsen.
Have a great and Fluttericious day.
If you found this article helpful click and hold 👏 a button and show some love and help others to find this article.
Feeling more generous, you can buy me a cup of tea.
If you got any questions or suggestion then you can connect with me anytime over Twitter.