首页 > 解决方案 > 如何在 Dart 中使用复杂的参数调用 super()?

问题描述

根据我的研究,在 Dart 中,您必须在构造函数的函数体之外调用 super 。

假设这种情况:

/// Unmodifiable given class
class Figure{
  final int sides;
  const Figure(this.sides);
}

/// Own class
class Shape extends Figure{
  Shape(Form form){
    if(form is Square) super(4);
    else if(form is Triangle) super(3);
  }
}

这会引发分析错误(超类没有 0 参数构造函数并且表达式 super(3) 没有计算为函数,因此无法调用它)。我怎样才能实现示例的所需功能?

标签: dart

解决方案


在 Dart 中调用超级构造函数时使用了初始化列表

class Shape extends Figure{
  Shape(Form form) : super(form is Square ? 4 : form is Triangle ? 3 : null);
}

如果您需要执行语句,您可以添加一个工厂构造函数,该构造函数转发给一个(私有)常规构造函数,例如

class Shape extends Figure{

  factory Shape(Form form) {
    if (form is Square) return new Shape._(4);
    else if(form is Triangle) return new Shape._(3);
  }
  Shape._(int sides) : super(sides)
}

推荐阅读