Article Directory
Recently I am learning Flutter, and I still encounter the advanced function of Extension, so it is necessary to learn about it.
Flutter is based on the language Dart. In version 2.7 of Dart, an important grammatical function is newly added, called extension. Add new functions to Extension
the main 给已经存在的类添加新的member function
function of. Through extension, we can add some convenient functions to common classes such as Iterable and String.
Extend the functionality of String
We create a file named "string_parser_extension.dart" with the following content.
extension ParseNumbers on String {
int parseInt() {
return int.parse(this);
}
double parseDouble() {
return double.parse(this);
}
}
It should be noted that in the extension function, we can 通过this
access the string 原有的其它方法
. This here refers to 当前的string instance
.
Use extended functions
To use these two extension functions, 只需要 import
'{file path}:string_parser_extension.dart', then we can use these two functions for the string type in the code.
final d = '2';
print(d.parseInt());
In addition, the following writing methods are also possible:
dynamic v = '1';
print(v.parseInt());
var v = '1';
print(v.parseInt());
In other words, adding convenient functions to the String class through extensions can increase usage and simplify the code.