目次

prefer_constructors_over_static_methods

インスタンスを作成するには、静的メソッドではなくコンストラクタを定義することをお勧めします。

このルールは、Dart 2.0から利用可能です。

詳細

#

推奨 インスタンスを作成するには、静的メソッドではなくコンストラクタを定義してください。

ほとんどの場合、インスタンス化をより明確にするため、静的メソッドではなく名前付きコンストラクタを使用する方が理にかなっています。

悪い例

dart
class Point {
  num x, y;
  Point(this.x, this.y);
  static Point polar(num theta, num radius) {
    return Point(radius * math.cos(theta),
        radius * math.sin(theta));
  }
}

良い例

dart
class Point {
  num x, y;
  Point(this.x, this.y);
  Point.polar(num theta, num radius)
      : x = radius * math.cos(theta),
        y = radius * math.sin(theta);
}

使用方法

#

prefer_constructors_over_static_methodsルールを有効にするには、analysis_options.yamlファイルのlinter > rulesの下にprefer_constructors_over_static_methodsを追加します。

analysis_options.yaml
YAML
linter:
  rules:
    - prefer_constructors_over_static_methods