no-magic-number

Same as no-magic-number in Dart Code Metrics

Group
Style
Path
lint/style/no-magic-number
Default
Off, opt in
Origin
Dart Code Metrics
Rule
292 of 512

Flags unnamed numeric literals (magic numbers) used inline in expressions.

A bare number buried in logic hides its meaning and invites duplication; extracting it to a named constant documents intent and gives the value a single point of change. To keep the rule practical it exempts contexts where a literal is self-explanatory or unavoidable: variable, field, and top-level initializers, direct elements of list/set literals, entries of const maps, literal array indices, any const context (const constructors, const collections), and DateTime constructor arguments. Detection also reaches through cascades, records, switch expressions, and assert statements so literals in those positions are still caught. Values on the allow-list are never treated as magic.

Options

allowed (list of numbers, default: [-1, 0, 1]) — numeric values never treated as magic numbers.

Invalid

example.dartdart
// Test cases for no-magic-number. Each literal sits in a non-exempt position
// (default allow-list is [-1, 0, 1]).

// A literal in a condition is flagged.
void threshold(int count) {
  if (count > 100) {
    print(count);
  }
}

// A for-loop condition literal is flagged (the initializer is a var decl).
void loop() {
  for (var i = 0; i < 10; i++) {
    print(i);
  }
}

// A non-const constructor argument is flagged.
Widget build() {
  return SizedBox(height: 12);
}

// A non-const map's value is flagged.
Map<String, int> config() {
  return {'timeout': 5000};
}

// Arithmetic on a magic number in an expression statement is flagged.
void compute(int value) {
  print(value * 100);
}
Avoid using magic numbers. Extract them to named constants or variables.
5void threshold(int count) {
6 if (count > 100) {
Avoid using magic numbers. Extract them to named constants or variables.
12void loop() {
13 for (var i = 0; i < 10; i++) {
Avoid using magic numbers. Extract them to named constants or variables.
19Widget build() {
20 return SizedBox(height: 12);
Avoid using magic numbers. Extract them to named constants or variables.
24Map<String, int> config() {
25 return {'timeout': 5000};
Avoid using magic numbers. Extract them to named constants or variables.
29void compute(int value) {
30 print(value * 100);

Valid

example.dartdart
// Good examples for no-magic-number. Every non-allowed literal here sits in a
// position dcl exempts: allow-list, variable/field initializer, collection
// literal, const constructor, const map, DateTime, or index expression.

// Allowed numbers (-1, 0, 1) are never magic, in any position.
int allowed() => compute(0) + compute(1) + compute(-1);

// Variable and field initializers are exempt (VariableDeclaration ancestor).
final topLevelTimeout = 3000;

class Config {
  final int maxRetries = 5;
  static const int port = 8080;

  int scaled(int value) {
    final factor = 100;
    return factor;
  }
}

// Direct elements of a list/set literal are exempt.
List<int> sizes() => [12, 24, 48];

// A const constructor exempts its whole argument subtree.
Widget spacer() => const SizedBox(height: 12, width: 800);

// A const map is exempt, and so is a DateTime constructor.
Map<String, int> durations() => const {'short': 15, 'long': 60};

DateTime epoch() => DateTime(2020, 1, 1);

// A literal used directly as an index is exempt.
int firstFew(List<int> xs) => xs[5];

Configure no-magic-number

Set its severity in falcon.json. See the configuration guide.

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "no-magic-number": "error"
      }
    }
  }
}

Or silence one occurrence with a suppression comment; the reason is required.

example.dartdart
// falcon-ignore lint/style/no-magic-number: <reason>
  • no-object-declarationno-object-declaration

    Flags class members declared with the type Object (or Object?).

  • no-runtime-type-to-stringno_runtimeType_toString

    Avoid calling toString() on runtimeType.

  • non-constant-identifier-namesnon_constant_identifier_namesrecommended

    Flags non-constant identifiers that are not written in lowerCamelCase.

  • omit-local-variable-typesomit_local_variable_types

    Flags local variable type annotations that repeat the initializer's type.

  • only-throw-errorsonly_throw_errorsrecommended

    Only throw instances of classes that extend Exception or Error.

  • package-namespackage_namesrecommendedcross-file

    Require package names to be valid lower_case_with_underscores identifiers.

  • parameter-assignmentsparameter_assignments

    Don't reassign parameters of functions, methods, or constructors.

  • parameters-ordering

    Requires named parameters to follow the explicitly configured alphabetical order.