正文
如何在Dart中使用Extension
寫出干凈整潔的代碼?
Dart最近宣布支持Extension方法,你也可以在項目中使用這個牛X的功能了!!!本文旨在展示我是如何在項目中使用Extension
方法的。
在我的Flutter項目中,我經常使用Enum,但是集成Enum
和Extension
方法會讓代碼變得更簡潔易讀。
假設你寫了一個Enum,然后你根據這個Enum的值返回不同的文本。在以前,我會使用IIFE(media post)在widget
中使用switch
語句,在函數表達式中調用匿名方法,雖然在Dart中這很常用,但這種模式會產生很多面條式代碼,如下例所示。另外,如果需要在其他地方添加相同的文本,則必須復制整個代碼片段,而不是僅僅進行函數調用。
Text((){
switch (selectedColor) {
case SelectedColor.PrimaryColor:
return 'This is the Primary Color';
case SelectedColor.SecondaryColor:
return 'This is the Secondary Color';
default:
return 'SelectedScheme Title is null';
}
}()),
Text((){
switch (selectedColor) {
case SelectedColor.PrimaryColor:
return 'This is the Primary Color';
case SelectedColor.SecondaryColor:
return 'This is the Secondary Color';
default:
return 'SelectedScheme Title is null';
}
}()),
另外,如果你想要根據Enum值修改文本,你甚至需要給PrimaryColor
和SecondaryColor
再寫一個IIFE。
現在,你不用為此而煩惱,你只需要擴展你的Enum
並實現一個擴展方法就可以搞定這一切。使用這種方式可以實現相同的功能,並且代碼更簡潔易讀。擴展枚舉對Java開發者非常重要,枚舉本應支持擴展!
enum SelectedColor {
primaryColor,
secondaryColor,
}
extension SelectedColorExtension on SelectedColor {
String get name => describeEnum(this);
String get displayTitle {
switch (this) {
case SelectedColor.PrimaryColor:
return 'This is the Primary Color';
case SelectedColor.SecondaryColor:
return 'This is the Secondary Color';
default:
return 'SelectedScheme Title is null';
}
}
}
Flutter Foundation
中定義的describeEnum()
函數從enumEntry.toString()
返回值中中剝離了枚舉類名,僅返回了枚舉值的字符串。我提供了一個自定義的替代實現,你可以將它用於其他Dart
項目。
String describeEnum(Object enumEntry) {
final String description = enumEntry.toString();
final int indexOfDot = description.indexOf('.');
assert(indexOfDot != -1 && indexOfDot < description.length - 1);
return description.substring(indexOfDot + 1);
}
在示例代碼中,我給枚舉擴展了4個方法displayTitle()
, displayColorChangeText()
, color()
, 和getRandomSelectedColor()
。當調用displayTitle()
方法時,你會發現明顯比IIFE更模塊化,更簡潔,更新枚舉添加新枚舉值也會變得更加容易,添加新的擴展方法也非常容易,比如添加color()
函數來改變文本顏色,只需要在Extension
添加新方法就可以了。
Flutter Gallery
中使用handling category demos
來演示Enum
中使用Extension
。
結束語
Extension Method是Dart
中的一個強大工具,使用它你可以寫出更簡潔易讀、更易擴展的代碼。
學習更多的Dart設計模式,請看3 Cool Dart Patterns for everyday programming in Flutter