[搬運]Dart之枚舉中使用擴展


原文在這里

正文

如何在Dart中使用Extension寫出干凈整潔的代碼?

avatar

Dart最近宣布支持Extension方法,你也可以在項目中使用這個牛X的功能了!!!本文旨在展示我是如何在項目中使用Extension方法的。

在我的Flutter項目中,我經常使用Enum,但是集成EnumExtension方法會讓代碼變得更簡潔易讀。

假設你寫了一個Enum,然后你根據這個Enum的值返回不同的文本。在以前,我會使用IIFEmedia 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值修改文本,你甚至需要給PrimaryColorSecondaryColor再寫一個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);
}

在CodePen中運行示例代碼

在示例代碼中,我給枚舉擴展了4個方法displayTitle(), displayColorChangeText(), color(), 和getRandomSelectedColor()。當調用displayTitle()方法時,你會發現明顯比IIFE更模塊化,更簡潔,更新枚舉添加新枚舉值也會變得更加容易,添加新的擴展方法也非常容易,比如添加color()函數來改變文本顏色,只需要在Extension添加新方法就可以了。

Flutter Gallery中使用handling category demos來演示Enum中使用Extension

結束語

Extension MethodDart中的一個強大工具,使用它你可以寫出更簡潔易讀、更易擴展的代碼。

學習更多的Dart設計模式,請看3 Cool Dart Patterns for everyday programming in Flutter


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM