sdk
sdk copied to clipboard
Analyzer makes a suboptimal suggestion for `const` with collections
In the following code:
final x = Column(
mainAxisAlignment: y,
children: [
SizedBox(),
Expanded(child: Padding(padding: EdgeInsets.zero)),
Placeholder(),
],
);
The analyzer suggests adding a const modifer before the list literal as expected:
children: const [...]
However, if there is a condition as such:
children: kIsWeb ? [
SizedBox(),
Expanded(child: Padding(padding: EdgeInsets.zero)),
Placeholder(),
] : []
The analyzer suggests applying const on individual elements instead:
children: kIsWeb ? [
const SizedBox(),
const Expanded(child: Padding(padding: EdgeInsets.zero)),
const Placeholder(),
] : []
But I would expect the optimal suggestion to be:
children: kIsWeb ? const [
SizedBox(),
Expanded(child: Padding(padding: EdgeInsets.zero)),
Placeholder(),
] : const []
(Note that the analyzer currently also does not suggest adding a const before the empty list in the else branch.)
Summary: The analyzer incorrectly suggests applying const to individual elements within a conditional list literal instead of suggesting const on the entire list, leading to suboptimal code suggestions and missing suggestions for empty lists in the else branch.
Sounds like a recommendation coming from a lint (prefer_const_something, likely).
Enforcing this is the responsibility of the prefer_const_literals_to_create_immutables lint. The suggestion to convert each element of the list comes from the prefer_const_constructors lint. Hence, in this specific case, effectively prefer_const_constructors takes precedence and prefer_const_literals_to_create_immutables fails to detect this.