Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Resolved warnings false detection in ColorScheme definition #73

Merged
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ class MyWidget extends StatelessWidget {
// expect_lint: avoid_hardcoded_color
const ColoredBox(color: Colors.green),
ColoredBox(color: Theme.of(context).colorScheme.primary),

ColoredBox(color: _colorScheme.primary),
const ColoredBox(color: Colors.transparent),
],
);
}
}
ColorScheme get _colorScheme => const ColorScheme.dark(
primary:Color.fromRGBO(0, 255, 0, 1),
);
17 changes: 15 additions & 2 deletions packages/altive_lints/lib/src/lints/avoid_hardcoded_color.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/listener.dart';
Expand Down Expand Up @@ -48,7 +49,7 @@ class AvoidHardcodedColor extends DartLintRule {
context.registry.addInstanceCreationExpression((node) {
final typeName = node.staticType?.getDisplayString();

boywithdv marked this conversation as resolved.
Show resolved Hide resolved
if (typeName == 'Color') {
if (typeName == 'Color' && !_isInsideColorScheme(node)) {
reporter.atNode(node, _code);
}
});
Expand All @@ -63,7 +64,7 @@ class AvoidHardcodedColor extends DartLintRule {
if (node.identifier.name == 'transparent') {
return;
}
if (_isColorType(returnType)) {
if (_isColorType(returnType) && !_isInsideColorScheme(node)) {
reporter.atNode(node, _code);
}
}
Expand All @@ -78,4 +79,16 @@ class AvoidHardcodedColor extends DartLintRule {
type.getDisplayString() == 'MaterialColor' ||
type.getDisplayString() == 'MaterialAccentColor');
}

bool _isInsideColorScheme(AstNode node) {
var parent = node.parent;
while (parent != null) {
if (parent is InstanceCreationExpression &&
parent.staticType?.getDisplayString() == 'ColorScheme') {
return true;
}
parent = parent.parent;
}
return false;
}
}