no-magic-number
Warns when number literals are used outside of named constants or variables.
Assigning repeating literals to variables helps avoid inconsistencies when only one of the repeated values is updated.
This rule excludes common constants (by default: -1, 0 and 1) and literals inside DateTime
constructor as there is no way to create const DateTime
and extracting each int
argument to separate named constant is far too inconvenient.
⚙️ Config
Set allowed
(default is [-1, 0, 1]
) to configure the list of allowed numbers.
Set allow-only-once
(default is false
) to allow magic numbers that are used one time within a file (example).
Set ignore-instances
(default is false
) to ignore magic numbers when creating instances (example).
analysis_options.yaml
dart_code_metrics:
rules:
- no-magic-number:
allowed: [3.14, 100, 12]
allow-only-once: false
ignore-instances: false
Example
❌ Bad:
// LINT: Avoid magic numbers. Try extracting them to named constants or variables.
double circleArea(double radius) => 3.14 * pow(radius, 2);
final finalPrice = cart.productCount > 4 // LINT: Avoid magic numbers. Try extracting them to named constants or variables.
? cart.totalPrice - (cart.totalPrice * 0.25); // LINT: Avoid magic numbers. Try extracting them to named constants or variables.
: cart.totalPrice
✅ Good:
const pi = 3.14;
double circleArea(double radius) => pi * pow(radius, 2); // Correct, moved to a named constant
const productCountThresholdForDiscount = 4;
const discount = 0.25;
final finalPrice = cart.productCount > productCountThresholdForDiscount
? cart.totalPrice - (cart.totalPrice * discount);
: cart.totalPrice
final someDay = DateTime(2006, 12, 1); // Correct, DateTime has no const constructor
Example with "allow-only-once"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- no-magic-number:
allow-only-once: true
✅ Good:
double circleArea(double radius) => 3.14 * pow(radius, 2); // Correct, used only once
Example with "ignore-instances"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- no-magic-number:
ignore-instances: true
✅ Good:
MyWidget(
width: 100,
height: 200, // Correct, instance creations are ignored
);