linter icon indicating copy to clipboard operation
linter copied to clipboard

prefer_const_constructors_in_immutables: doesn't trigger if class has no constructor

Open goderbauer opened this issue 2 years ago • 2 comments

prefer_const_constructors_in_immutables only triggers when an @immutable class has a non-const constructor. If no constructor is explicitly defined, the lint doesn't trigger and you - unfortunately - end up with an immutable class that cannot be const constructed. I think, the lint should remind people to add an explicit const constructor in those cases as well.

// 🔥 no reminder is given that this immutable class should have a const constructor.
@immutable
class Foo {

}

// lint triggers as expected.
@immutable
class Bar {
  Bar();
}

This could be relevant for some Flutter widgets that don't take in any arguments and because of this developers don't see a reason to add an explicit constructor. They are now missing an opportunity to create a const instance of their widget.

goderbauer avatar May 25 '22 20:05 goderbauer

💯

I think you're totally right. It'll be interesting to see if this catches any violations in flutter and internally...

pq avatar May 25 '22 22:05 pq

This seems to require some changes on the analyzer API. For now there is a context.canBeConstConstructor(node) but in the case of default constructor there is no node corresponding to this constructor. All we have is a synthetic ConstructorElement. @scheglov any idea if this is possible without API change on analyzer?

a14n avatar May 30 '22 13:05 a14n