no_magic_number
A no_magic_number
rule which forbids having numbers without variable
There is a number of exceptions, where number literals are allowed:
- Collection literals;
- DateTime constructor usages;
- In constant constructors, including Enums;
- As a default value for parameters;
- In constructor initializer lists;
Example config:
custom_lint:
rules:
- no_magic_number:
allowed: [12, 42]
allowed_in_widget_params: true
Example
BAD:
double circumference(double radius) => 2 * 3.14 * radius; // LINT
bool canDrive(int age, {bool isUSA = false}) {
return isUSA ? age >= 16 : age > 18; // LINT
}
class Circle {
final int r;
const Circle({required this.r});
}
Circle(r: 5); // LINT
var circle = Circle(r: 10); // LINT
final circle2 = Circle(r: 10); // LINT
GOOD:
const pi = 3.14;
const radiusToDiameterCoefficient = 2;
double circumference(double radius) =>
radiusToDiameterCoefficient * pi * radius;
const usaDrivingAge = 16;
const worldWideDrivingAge = 18;
bool canDrive(int age, {bool isUSA = false}) {
return isUSA ? age >= usaDrivingAge : age > worldWideDrivingAge;
}
class Circle {
final int r;
const Circle({required this.r});
}
const Circle(r: 5);
const circle = Circle(r: 10)
Allowed
class ConstClass {
final int a;
const ConstClass(this.a);
const ConstClass.init() : a = 10;
}
enum ConstEnum {
// Allowed in enum arguments
one(1),
two(2);
final int value;
const ConstEnum(this.value);
}
// Allowed in const constructors
const classInstance = ConstClass(1);
// Allowed in list literals
final list = [1, 2, 3];
// Allowed in map literals
final map = {1: 'One', 2: 'Two'};
// Allowed in indexed expression
final result = list[1];
// Allowed in DateTime because it doesn't have const 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]) {}
}
Parameters
allowed_numbers (Iterable<num>)
List of numbers excluded from analysis
Defaults to numbers commonly used for increments and index access:
[-1, 0, 1]
.
allowed_in_widget_params (bool)
Boolean flag, toggles analysis for raw numbers within Widget constructor call parameters.
When flag is set to false
, it warns about any non-const numbers in
your layout:
Widget build() {
return MyWidget(
decoration: MyWidgetDecoration(size: 12), // LINT
value: 23, // LINT
child: const SizedBox(width: 20) // allowed for const
);
}
When flag is set to true
, it allows non-const layouts with raw numbers:
Widget build() {
return MyWidget(
decoration: MyWidgetDecoration(size: 12), // OK
value: 23, // OK
child: const SizedBox(width: 20) // OK as it was
);
}