“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”
preface
Extension is a way to add extended functionality to a class without changing the class or creating a subclass. Flexible use of Extension to extend basic classes has significantly improved the development efficiency.
🌰, for example, extends int
Xiaohong met a requirement in the development project: to convert the value of minutes into a string of units
/// The usual way to write it is to encapsulate the transformation method
///Encapsulation method: the amount to the string to retain two decimal places
String convertPointToUnit(int num) {return (num.toDouble() / 100).toStringAsFixed(2);
}
///use
void main(){
int num = 100;
var result = convertPointToUnit(num);
print(result); // Prints 1.00
}
Copy the code
The same functionality can be developed with Extension more succinct, as follows:
/// Extend the int class with Extension by adding the method moneyString
extension ExInt on int {
/// The amount goes to the string with two decimal digits reserved
/// 100 = > 1.00
String get moneyString => (this.toDouble() / 100).toStringAsFixed(2);
}
import ../ExInt.dart;
///use
void main(){
int num = 100;
print(num.moneyString);
}
Copy the code
When extended, it is used directly as a member method of that type. Extension is like gene assignment, bestowing abilities (methods) directly to the host.
Extended demonstrations of various scenarios
- Extend the implementation of enumerations
enum FruitEnum { apple, banana }
extension ExFruitEnum on FruitEnum {
String get name {
switch (this) {
case FruitEnum.apple:
return "apple";
case FruitEnum.banana:
return "banana"; }}}///String match enumeration
FruitEnum generateFruit (String fruitType){
if(fruitType == FruitEnum.apple.name){
return FruitEnum.apple;
} else if(fruitType == FruitEnum.banana.name){
returnFruitEnum.banana; }}Copy the code
- Extensions apply to generics:
// Extend the list method
extension ExList<T> on List<T> {
// Extend the operator
List<T> operator -() => reversed.toList();
// A linked list is split into two
List<List<T>> split(int at) => <List<T>>[sublist(0, at), sublist(at)];
}
Copy the code
- Extend the application of widgets
We’ll have similar controls
Column(
children: <Widget>[
Container(
paddint: const EdgeInsets.all(10)
child: AWidget(),
),
Container(
paddint: const EdgeInsets.all(10)
child: BWidget(),
),
Container(
paddint: const EdgeInsets.all(10)
child: CWidget(),
),
]
)
Copy the code
There’s a lot of redundancy in the code, right? Let’s extend with extension:
extension ExWidget on Widget {
Widget paddingAll(double padding) {
return Container(
paddint: const EdgeInsets.all(padding)
child: this,); }}Copy the code
Then we can change it to:
Column(
children: <Widget>[
AWidget().paddingAll(10),
BWidget().paddingAll(10),
CWidget().paddingAll(10),])Copy the code
Feel free to share more interesting uses in the comments section