Extensions in Flutter
Arpan Bhatia
8+ Years Experience, I am looking for New Opportunities, Contact at: 7906156955 || Sr. Developer @Team Computers Mobile Team || Android || Core Java || Kotlin || Flutter || Dart || Jetpack Components ||Jetpack Compose UI
In Flutter extensions allowed to you to add some new functionality to existing class without modified their original implementation. Extensions are particularly useful for adding helper method or computed properties to a class.
Code Syntax for using Extension Functionality in Flutter:
We have a class named Person as below:
class Person
{
int name ;
int age;
Person(this.name, this.age)
}
Now we will add a method in this Person class using Extension Functionality:
we use extension keyword to make the extension and on keyword to specify typed that being extended. Like in following example Person class has been extended using on keyword.
extension PersonDetail on Person
{
String getDetails()
{
return 'name is $name and age is $age'
}
}
Let us call the this method in out main function:
var persondetail = Person(28,"arpan");
print(persondetail.getDetails());
Output : name is arpan and age is 28
Note: You can not create the object of extension in Dart. Extensions are not type or classes.
领英推荐
You can extend the functionality of existing classes, even if you don't have access to their source code. The class or type comes from an external library or package (like Flutter's String, List, or Date Time classes) we don't have direct control over source code so extensions can be useful to add the functionality of these classes. Let we take a example with following code:
We will make the a extension function of String class to check that String is Palindrome or not
extension isStringPalindrome on String
{
bool isPalindrome()
{
int length = this.length;
for (int i = 0; i < length ~/ 2; i++)
{
if (this[i] != this[length - 1 - i])
{
return false;
}
}
return true;
}
void main()
{
String str= 'radar';
print(str.isPalindrome());
}
Output: true
In the above example we have make a extension function "isPlaindrome()" of String class.
Note: The this keyword in Dart, especially within an extension function, refers to the instance of the type on which the extension is being applied. It provides access to the current object or value being extended.
Conclusion:
Extension functions enhance productivity by enabling developers to write clean, readable, and maintainable code while adhering to the principles of encapsulation and modular design. They are a valuable tool for extending and customizing the behavior of classes in a non-intrusive way.