prefer_constructors_over_static_methods
Prefer defining constructors instead of static methods to create instances.
This rule is available as of Dart 2.0.
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:
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));
}
}
GOOD:
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);
}
Usage
#To enable the prefer_constructors_over_static_methods
rule,
add prefer_constructors_over_static_methods
under linter > rules in your
analysis_options.yaml
file:
analysis_options.yaml
yaml
linter:
rules:
- prefer_constructors_over_static_methods
除非另有说明,文档之所提及适用于 Dart 3.5.4 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。