子类const构造函数

时间:2018-11-01 04:28:16

标签: dart flutter

要在其他类中将CircularBorderRadius.zero用作默认值,它必须为const。有没有办法为const制作CircularBorderRadius构造函数?

class CircularBorderRadius extends BorderRadius {

  static CircularBorderRadius zero = CircularBorderRadius.only();

  CircularBorderRadius.all(double radius)
      : this.only(
    topLeft: radius,
    topRight: radius,
    bottomLeft: radius,
    bottomRight: radius,
  );

  CircularBorderRadius.only({
    double topLeft,
    double topRight,
    double bottomLeft,
    double bottomRight,
  }) : super.only(
      topLeft: topLeft == null ? null : Radius.circular(topLeft),
      topRight: topRight == null ? null : Radius.circular(topRight),
      bottomLeft: bottomLeft == null ? null : Radius.circular(bottomLeft),
      bottomRight: bottomRight == null ? null : Radius.circular(bottomRight));

}

示例

class CustomWidget {
  // ...

  CustomWidget({
    this.borderRadius = CircularBorderRadius.zero, // <—— "error: Default values of an optional parameter must be constant."
  });

  // ...
}

1 个答案:

答案 0 :(得分:1)

为了使您的CircularBorderRadius.only常量,可选参数也应为const,因此根据您的代码,您不能这样做。

但是您可以尝试执行以下操作:

        class CustomWidget {
          // ...

          CustomWidget({
            CircularBorderRadius borderRadius, 
          }): this.borderRadius = borderRadius ?? CircularBorderRadius.zero;

          final CircularBorderRadius borderRadius;
          // ...
        }