Extend your capabilities with Extension Methods — Flutter💙
We all love shortcode that does the work. So dart has provided a great feature called Extension Methods which you can use on different data types!
Who doesn’t love small, short, sweet working code? We all have written long messy code to get the work done! But, Dart knows the pain and hence we have Extensions Methods! You might feel it’s similar to our normal, user-defined functions, and it actually is a lot similar!
We have seen the following syntax:
Text(capitalFirstChar('hello world'))
...String capitalFirstChar(String data) {
return data.split(" ").map((str) => str[0].toUpperCase() + str.substring(1)).join(" ");
}
So this is a method that takes String as the parameter, capitalizes the first letter of each word and then returns the new string.
However, what if you can do the same like the following:
Text('hello world. how are you'.capitalFirstChar())
This can be achieved using Extension Methods!
Extension Methods are special methods provided in Dart that can be directly used on data types to perform certain operations!
To create an extension on String data type, you can do the following for the above capitalFirstChar
method:
extension StringExtension on String {
String capitalFirstChar() {
return this.split(" ").map((str) => str[0].toUpperCase() + str.substring(1)).join(" ");
}
}
This will create an extension method that can be used on String data types. Here, you can access the string on which the method was called using this keyword!
Now, to access this method, you just need to import the file where you have created the above function and use it with any String!
Text('hello world. how are you'.capitalFirstChar()),
Here’s a small example for your reference:
string_extension.dart
main.dart:
Feel free to clone the repository from GitHub!
Don’t stop, until you are breathing!💙
- Abhishek Doshi