Skip to content

Commit

Permalink
Allow magic numbers for default values
Browse files Browse the repository at this point in the history
  • Loading branch information
vova-beloded-solid committed Nov 15, 2023
1 parent 1ce6a91 commit 84a84df
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
7 changes: 6 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 @@ -69,7 +69,8 @@ class NoMagicNumberRule extends SolidLintRule<NoMagicNumberParameters> {
.where(_isNotInsideConstConstructor)
.where(_isNotInDateTime)
.where(_isNotInsideIndexExpression)
.where(_isNotInsideEnumConstantArguments);
.where(_isNotInsideEnumConstantArguments)
.where(_isNotDefaultValue);

for (final magicNumber in magicNumbers) {
reporter.reportErrorForNode(code, magicNumber);
Expand Down Expand Up @@ -122,4 +123,8 @@ class NoMagicNumberRule extends SolidLintRule<NoMagicNumberParameters> {
null;

bool _isNotInsideIndexExpression(Literal l) => l.parent is! IndexExpression;

bool _isNotDefaultValue(Literal literal) {
return literal.thisOrAncestorOfType<DefaultFormalParameter>() == null;
}
}
22 changes: 21 additions & 1 deletion lint_test/no_magic_number_test.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// ignore_for_file: unused_local_variable, prefer_match_file_name
// ignore_for_file: unused_local_variable
// ignore_for_file: prefer_match_file_name
// ignore_for_file: avoid_unused_parameters
// ignore_for_file: no_empty_block

/// Check the `no_magic_number` rule
Expand Down Expand Up @@ -55,3 +58,20 @@ void fun() {
// Allowed in DateTime because it doesn't have cons constructor
final apocalypse = DateTime(2012, 12, 21);
}

// Allowed for defaults in constructors and methods.
class DefaultValues {
final int value;

DefaultValues.named({
this.value = 2,
});

DefaultValues.positional([
this.value = 3,
]);

void methodWithNamedParam({int value = 4}) {}

void methodWithPositionalParam([int value = 5]) {}
}

0 comments on commit 84a84df

Please sign in to comment.