[搬运]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

posted @ 2020-07-21 10:43  痴人指路  阅读(3254)  评论(0编辑  收藏  举报