prefer_ constructors_ over_ static_ methods
Prefer defining constructors instead of static methods to create instances.
Details
#PREFER defining constructors instead of static methods to create instances.
In most cases, it makes more sense to use a named constructor rather than a static method because it makes instantiation clearer.
BAD:
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));
}
}
GOOD:
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);
}
Enable
#
To enable the
prefer_constructors_over_static_methods
rule, add
prefer_constructors_over_static_methods
under
linter > rules
in your
analysis_options.yaml
file:
linter:
rules:
- prefer_constructors_over_static_methods
If you're instead using the YAML map syntax to configure linter rules,
add
prefer_constructors_over_static_methods: true
under
linter > rules:
linter:
rules:
prefer_constructors_over_static_methods: true
Unless stated otherwise, the documentation on this site reflects Dart 3.9.2. Report an issue.