sdk icon indicating copy to clipboard operation
sdk copied to clipboard

Analyzer makes a suboptimal suggestion for `const` with collections

Open amal-stack opened this issue 1 year ago • 1 comments
trafficstars

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.)

amal-stack avatar Aug 28 '24 08:08 amal-stack

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.

dart-github-bot avatar Aug 28 '24 08:08 dart-github-bot

Sounds like a recommendation coming from a lint (prefer_const_something, likely).

lrhn avatar Aug 28 '24 14:08 lrhn

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.

amal-stack avatar Aug 28 '24 14:08 amal-stack