Dart Extension
Hello guys!! In this article you will learn how to use extension in dart. After reading this article you will be able to use extension in dart.
What is extension ?
Using extension we can write or define our own methods or functions for a existing classes e.g: int, String etc.
Why we need extension ?
Suppose we want to parse a string into int. We can do this using
int.parse("45")
But what if we want to do like this.
"45".parseToInt()
Above code is easy to use. We can achieve this thing using a extension.
Syntax for defining extension
extension extension_name on class_name {
// Write your methods here.
}
Now we will define extension on string.
extension ParseToInt on String {
int parseToInt(){return int.parse(this);}
}
Here our extension name is ParseToInt, we can give any name to it and method name is parseToInt, this method returns integer value. We can use this extension on any string, because it's defined for all strings. It gives FormateException when we pass a string which can not be converted into int.
Using this keyword we are getting the string value, that's why we don't need to define argument for parseToInt() .
Now we can use extension on any string. Using dot we can access all extensions which are defined for strings.
void main() {
int value = "45".parseToInt();
print(value);
}
// Output; 45
You can learn more about extension on this
Thank you guys for reading article, If you have any doubt than you can ask me on linkedin.
Flutter | Dart | AngularDart | Firebase | RiverPod | GetX | RxDart | Android
1 年https://pub.dev/packages/awesome_extensions