Skip to main content

prefer_constructors_over_static_methods

Static method should be a constructor.

Description

#

The analyzer produces this diagnostic when a static method returns a newly created instance of the class and could, therefore, be a constructor.

Example

#

The following code produces this diagnostic because the static method all could be a constructor:

dart
class C {
  final int a, b, c;
  C(this.a, this.b, this.c);
  static C all(int i) => C(i, i, i);
}

Common fixes

#

Convert the static method to a named constructor:

dart
class C {
  final int a, b, c;
  C(this.a, this.b, this.c);
  C.all(int i) : a = i, b = i, c = i;
}