rspec/rules/S3689/dart/rule.adoc
2024-08-23 14:19:10 +02:00

74 lines
1.7 KiB
Plaintext

== Why is this an issue?
In Dart, `const` is used to declare compile-time constants. It can also be used to declare constant values, typically provided by https://dart.dev/language/constructors#constant-constructors[constant constructors]. This constructor, if used within `const` context will create an instance as a compile-time constant. This is an example of usage of a constant constructor:
Declaration
[source,dart]
----
class Person {
final int age;
final String name;
const Person(this.age, this.name);
}
----
Usage
[source,dart]
----
void f() {
var p = const Person(40, 'A');
var family = const [Person(40, 'A'), Person(39, 'B')];
}
----
When you're already inside the `const` context, there's no need to repeat the keyword. So instead of writing `const [const Person(40, 'A'), const Person(39, 'B')]` you can just write `const [Person(40, 'A'), Person(39, 'B')]`.
This rule raises an issue when `const` modifier was used within another `const` context
=== Noncompliant code example
[source,dart]
----
void f() {
var family = const [const Person(40, 'A'), const Person(39, 'B')];
}
----
=== Compliant solution
[source,dart]
----
void f() {
var family = const [Person(40, 'A'), Person(39, 'B')];
}
----
== Resources
* Dart Docs - https://dart.dev/tools/linter-rules/unnecessary_const[Dart Linter rule - unnecessary_const]
* Dart Docs - https://dart.dev/language/constructors#constant-constructors[Constant constructors]
* Dart Docs - https://dart.dev/language/classes[Dart classes]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Unnecessary 'const' keyword.
=== Highlighting
the const keyword
endif::env-github,rspecator-view[]