【问题标题】:How to add a constructor to an existing class in Dart?如何将构造函数添加到 Dart 中的现有类?
【发布时间】:2018-11-25 19:36:31
【问题描述】:

我想为一些常见的 UI 类创建一些便利/工厂构造函数。例如,文本样式:

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 中解决这个问题?

【问题讨论】:

    标签: class constructor dart


    【解决方案1】:

    像下面这样扩展 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 对象的顶级工厂函数。
    • 是的,太好了。我试图解释我们不能修改类。我们只能扩展它。
    • 这很棒。为了学术,如果我保留枚举并为超级构造函数构造一个参数列表怎么办:class TSExt extends TextStyle { //TSExt(Font font, Weight weight, double fontSize, Color color) : super(arguments); TSExt(Font font, Weight weight, double fontSize, Color color){ var args = { // ... }; super(args); } }
    • @GoldenJow 这似乎是个好主意,如果你测试了这个方法,请告诉我们
    猜你喜欢
    • 2019-07-21
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多