Rules / Complexity / unnecessary-const
unnecessary-const
Flags a redundant const keyword inside an already-const context.
Once an expression sits in a constant context — a const collection, the
arguments of a const constructor invocation, a const variable initializer,
or another const expression — every nested const is inferred and the
keyword is just noise; removing it leaves behavior unchanged. The rule
tracks const depth as it descends through const variable, field, and local
declarations and const expressions, flagging any explicit const marker
(on a new, list, map, set, or dot-shorthand) found at depth greater than
zero.
Invalid
example.dartdart
// Bad: a `const` keyword used where the context is already constant.
class Point {
final int x;
final int y;
const Point(this.x, this.y);
}
const outerList = const [1, 2, 3];
const outerMap = const {'a': 1};
const outerSet = const {1, 2, 3};
const point = const Point(1, 2);
const nestedList = [const [1, 2]];
const wrapped = [const Point(1, 2)];
Unnecessary `const` keyword inside an already-const context.
7
8const outerList = const [1, 2, 3];
∙
Unnecessary `const` keyword inside an already-const context.
8const outerList = const [1, 2, 3];
9const outerMap = const {'a': 1};
∙
Unnecessary `const` keyword inside an already-const context.
9const outerMap = const {'a': 1};
10const outerSet = const {1, 2, 3};
∙
Unnecessary `const` keyword inside an already-const context.
10const outerSet = const {1, 2, 3};
11const point = const Point(1, 2);
∙
Unnecessary `const` keyword inside an already-const context.
11const point = const Point(1, 2);
12const nestedList = [const [1, 2]];
∙
Unnecessary `const` keyword inside an already-const context.
12const nestedList = [const [1, 2]];
13const wrapped = [const Point(1, 2)];
∙
Valid
example.dartdart
// Good: `const` only where it is actually required to establish a constant.
class Point {
final int x;
final int y;
const Point(this.x, this.y);
}
const outerList = [1, 2, 3]; // implicitly const, no keyword needed
const point = Point(1, 2); // implicitly const
const nested = [
[1],
[2],
]; // all implicit
final runtime = const [1, 2, 3]; // final var: `const` needed to make it constant
var mutable = const <int>[1]; // `const` needed (context is not constant)
void f() {
const local = [1, 2, 3]; // implicitly const initializer
print(const [1, 2, 3]); // `const` needed: argument context is not constant
print(local);
}
How to configure
Set the severity of unnecessary-const in your falcon.json:
falcon.jsonjson
{
"linter": {
"rules": {
"complexity": {
"unnecessary-const": "error"
}
}
}
}