Skip to content

Commit

Permalink
Ignore magic numbers in widget parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
vova-beloded-solid committed Nov 16, 2023
1 parent fbc158d commit ddc63ff
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
23 changes: 22 additions & 1 deletion lib/lints/no_magic_number/no_magic_number_rule.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
// SOFTWARE.

import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/listener.dart';
import 'package:collection/collection.dart';
import 'package:custom_lint_builder/custom_lint_builder.dart';
import 'package:solid_lints/lints/no_magic_number/models/no_magic_number_parameters.dart';
import 'package:solid_lints/lints/no_magic_number/no_magic_number_visitor.dart';
Expand Down Expand Up @@ -71,7 +73,8 @@ class NoMagicNumberRule extends SolidLintRule<NoMagicNumberParameters> {
.where(_isNotInsideIndexExpression)
.where(_isNotInsideEnumConstantArguments)
.where(_isNotDefaultValue)
.where(_isNotInConstructorInitializer);
.where(_isNotInConstructorInitializer)
.where(_isNotWidgetParameter);

for (final magicNumber in magicNumbers) {
reporter.reportErrorForNode(code, magicNumber);
Expand Down Expand Up @@ -132,4 +135,22 @@ class NoMagicNumberRule extends SolidLintRule<NoMagicNumberParameters> {
bool _isNotInConstructorInitializer(Literal literal) {
return literal.thisOrAncestorOfType<ConstructorInitializer>() == null;
}

bool _isNotWidgetParameter(Literal literal) {
final instanceCreationExpression =
literal.thisOrAncestorOfType<InstanceCreationExpression>();

if (instanceCreationExpression == null) return true;

final staticType = instanceCreationExpression.staticType;

if (staticType is! InterfaceType) return true;

final widgetSupertype = staticType.allSupertypes.firstWhereOrNull(
(supertype) =>
supertype.getDisplayString(withNullability: false) == 'Widget',
);

return widgetSupertype == null;
}
}
15 changes: 15 additions & 0 deletions lint_test/no_magic_number_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,18 @@ class ConstructorInitializer {

ConstructorInitializer() : value = 10;
}

// Allowed for numbers in a Widget subtype parameters.
abstract interface class Widget {}

class StatelessWidget implements Widget {}

class MyWidget extends StatelessWidget {
final int size;

MyWidget({required this.size});
}

Widget build() {
return MyWidget(size: 12);
}

0 comments on commit ddc63ff

Please sign in to comment.