Rules / Style / prefer-initializing-formals
prefer-initializing-formals
Flags a constructor that copies a plain parameter into a same-named field.
Dart's initializing formals (this.x) declare the parameter and assign the
field in one step, so the manual copy — whether an initializer-list entry
: x = x or a body statement this.x = x; — is redundant boilerplate. The
rule is intentionally narrow: it fires only when the parameter name exactly
matches the field name and the parameter is a plain constructor parameter,
never an existing initializing (this.) or super (super.) formal, so cases
that already use the idiom or that transform the value are left untouched.
Invalid
example.dartdart
// Parameters copied verbatim into same-named fields.
class A {
int x;
A(int x) : x = x;
}
class B {
int y;
B(int y) { this.y = y; }
}
class C {
int a, b;
C(int a, int b) : a = a, b = b;
}
class D {
String name;
D(String name) : name = name;
}
class E {
int v;
E(int v) { this.v = v; }
}
Use an initializing formal to assign a parameter to a field.
3 int x;
4 A(int x) : x = x;
∙
Use an initializing formal to assign a parameter to a field.
8 int y;
9 B(int y) { this.y = y; }
∙
Use an initializing formal to assign a parameter to a field.
13 int a, b;
14 C(int a, int b) : a = a, b = b;
∙
Use an initializing formal to assign a parameter to a field.
13 int a, b;
14 C(int a, int b) : a = a, b = b;
∙
Use an initializing formal to assign a parameter to a field.
18 String name;
19 D(String name) : name = name;
∙
Use an initializing formal to assign a parameter to a field.
23 int v;
24 E(int v) { this.v = v; }
∙
Valid
example.dartdart
// Uses initializing formals, or assignments that are not a verbatim copy.
class A {
int x;
A(this.x);
}
class B {
int y;
B(int value) : y = value;
}
class C {
int a;
C(int a) : a = a + 1;
}
class D {
int v;
D(this.v);
}
class E {
int w;
E(int input) { w = input; }
}
class F {
int z;
F(this.z) { print(z); }
}
How to configure
Set the severity of prefer-initializing-formals in your falcon.json:
falcon.jsonjson
{
"linter": {
"rules": {
"style": {
"prefer-initializing-formals": "error"
}
}
}
}