prefer_const_literals_to_create_immutables false positive with bool.fromEnvironment
Originally raised at https://github.com/Dart-Code/Dart-Code/issues/4922 by @vatlnetwork.
The following code triggers prefer_const_literals_to_create_immutables:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class TopBar {
AppBar appBar(BuildContext context) {
return AppBar(
actions: [
if (kIsWeb) _button(context),
],
);
}
Widget _button(BuildContext context) {
return const Placeholder();
}
}
However adding const here (using the quick-fix) results in an error trying to run the application:
lib/main.dart(8,21): error G4020727C: Not a constant expression. [C:\Dev\Test Projects\dartcode_4922\build\windows\x64\flutter\flutter_assemble.vcxproj]
lib/main.dart(8,29): error G4020727C: Not a constant expression. [C:\Dev\Test Projects\dartcode_4922\build\windows\x64\flutter\flutter_assemble.vcxproj]
lib/main.dart(8,21): error G38BEFAAB: Method invocation is not a constant expression. [C:\Dev\Test Projects\dartcode_4922\build\windows\x64\flutter\flutter_assemble.vcxproj]
The issue only seems to happen when the if condition uses a const bool that uses bool.fromEnvironment.
I suspect the bug is in LintContext.canBeConst. It probably doesn't correctly detect that if and for elements can't be in a const literal.
Actually, an if-element can be in a const literal. This runs:
void main() {
const x = true;
const y = [
if (x) 7,
];
print(y);
}
Even a constant from bool.FromEnvironment is allowed:
import 'package:flutter/foundation.dart';
void main() {
const y = [
if (kIsWeb) 3,
];
print(y);
}
There is a bug in evaluating if-expressions with unknown const conditions.
Fixed with https://github.com/dart-lang/sdk/commit/47123f7e2d8a8d8fcea1fcff3b87be8698670a95