proposal: consider_const_constructor
#59001
Labels
area-devexp
For issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.
devexp-linter
Issues with the analyzer's support for the linter package
linter-lint-proposal
linter-set-flutter
linter-status-pending
P3
A lower priority bug or feature request
type-enhancement
A request for a change that isn't a bug
consider_const_constructor
Description
Classes with no non-final fields may benefit from defining a const constructor.
Details
https://dart.dev/guides/language/effective-dart/design#consider-making-your-constructor-const-if-the-class-supports-it
Kind
Suggest potential optimization. Make authors deliberately choose to use const OR ignore lint. Point to useful Effective Dart reference to help them decide.
Bad Examples
Good Examples
Discussion
Background
I came upon this when reviewing some code using bloc. I assumed the default constructor was const and almost suggested removing the const constructor from an event class:
I investigated more and learned that the default constructor is not const. Some resources I came across that helped me better understand why that's the case and when to use or not use const include:
const
Constructor parameters are never consideredconst
language#2000 (comment) and Constant constructor call should be legal in another constant constructor definition. language#823prefer_const_constructors_in_immutables
suggests defining const constructor, prefer_const_constructors suggests using const constructor.Considerations
Should lint just check that at least one const constructor exists? Or that all defined constructors are const?
Square.fromRadius
example above, should making one constructor const satisfy the lint check, or should both constructors be required to be made const (or ignored)?We could have a quick fix to create const constructor (if no constructors are defined) or make an existing constructor const, but it may be better to NOT have a quick fix so authors don't accidentally agree to maintaining a const constructor in their public API.
Is it worth having this lint?
This lint could also suggest annotating class with @immutable. (
consider_const_constructor
lint would be similar toprefer_const_constructors_in_immutables
).Discussion checklist
The text was updated successfully, but these errors were encountered: