- Published on
How to Extend a Class Adding Methods
In Flutter, you can extend a class by adding methods to it. This allows you to customize the behavior of existing classes and add new functionalities without modifying the original class. In this article, we will learn how to extend a class in Flutter and provide an example of extending the String
class to add a capitalize
method.
Example: Extending the String
Class
Let's say you want to add a capitalize
method to the String
class in Flutter. This method should capitalize the first letter of the string. Here's how you can do it:
extension StringExtension on String {
String capitalize() {
if (isEmpty) {
return this;
}
return '${this[0].toUpperCase()}${substring(1)}';
}
}
In the above code snippet, we use the extension
keyword to define an extension on the String
class. The StringExtension
is the name of the extension, and on String
specifies the class we are extending.
Inside the extension, we define the capitalize
method, which returns a new string with the first letter capitalized. We check if the string is empty and return it as is. Otherwise, we use string interpolation to capitalize the first letter and concatenate it with the rest of the string.
Now, you can use the capitalize
method on any string in your Flutter application. Here's an example:
void main() {
String name = "john doe";
String capitalized = name.capitalize();
print(capitalized); // Output: "John doe"
}
In the above example, we create a name
variable and assign it the value "john doe"
. We then call the capitalize
method on the name
variable and store the result in the capitalized
variable. Finally, we print the capitalized
variable, which outputs "John doe"
.
Summary
Extending a class in Flutter allows you to add custom methods and properties to existing classes. By extending the String
class and adding a capitalize
method, you can easily capitalize the first letter of any string in your Flutter application. Remember to use the extension
keyword to define the extension and specify the class you want to extend.