Class 如何向Dart中的现有类添加构造函数?

Class 如何向Dart中的现有类添加构造函数?,class,constructor,dart,Class,Constructor,Dart,我想为一些常见的UI类提供一些便利/工厂构造函数。例如,TextStyle: enum Font { AvenirNext, AvenirNextCondensed } enum Weight { Regular, Medium, DemiBold, Bold } // Use: // TextStyle(Fonts.AvenirNext, Weight.Medium, 20, Colors.white) // Maybe it can be even shorte

我想为一些常见的UI类提供一些便利/工厂构造函数。例如,TextStyle:

enum Font {
  AvenirNext,
  AvenirNextCondensed
}

enum Weight {
  Regular,
  Medium,
  DemiBold,
  Bold
}

// Use:
// TextStyle(Fonts.AvenirNext, Weight.Medium, 20, Colors.white)

// Maybe it can be even shorter?
// TextStyle(AvenirNext, Medium, 20, Colors.black)

如何在Dart中实现这一点?

像下面这样扩展TextStyle怎么样

class Font {
  static const AvenirNext = 'AvenirNext';
  static const AvenirNextCondensed = 'AvenirNextCondensed';
}

class Weight{
  static const Regular = FontWeight.w400;
  static const Medium = FontWeight.w500;
  static const DemiBold = FontWeight.w700;
  static const Bold = FontWeight.w900;
}

class CTextStyle extends TextStyle {
  CTextStyle(String f, FontWeight w, num s, Color c)
      : super(
          fontFamily: f,
          fontWeight: w,
          fontSize: s.toDouble(),
          color: c);
  }
}
用法:

TextStyle myCustom = CTextStyle(Font.AvenirNext, Weight.Medium, 20, Colors.black);

或者,甚至不创建类,只定义创建TextStyle对象的顶级工厂函数。是的,很好。我试图解释我们不能修改这个类。我们只能扩展它。这太棒了。为了学术起见,如果我保留枚举并为超级构造函数构造参数列表:类TSExt扩展TextStyle{//TSExtFont-font-font,Weight-Weight,double-fontSize,Color-Color:superarguments;TSExtFont-Weight,double-fontSize,Color-Color{var-args={//…};superargs;}@GoldenJow这似乎是个好主意,如果您测试了这种方法,请告诉我们