Skip to main content

no-magic-string

added in: 1.16.0
⚙️

Warns when string literals are used outside of named constants or variables.

This rule excludes some commonly used cases where a string constant is not expected (for example, regular expressions, String methods, annotations, default values, errors, exceptions and few more).

note

For this rule it's recommended to exclude the test folder.

dart_code_metrics:
...
rules:
...
- no-magic-string:
exclude:
- test/**
...

⚙️ Config

Set allow-only-once (default is false) to allow magic numbers that are used one time within a file.

Set ignored-invocations (default is [print, debugPrint]) to ignore strings in specific invocations.

dart_code_metrics:
...
rules:
...
- no-magic-string:
allow-only-once: true
ignored-invocations:
- print
- debugPrint

Example

❌ Bad:

void fn() {
final instance = SomeClass('something'); // LINT

if (instance.value == 'another') {} // LINT

instance.work('work'); // LINT
}

✅ Good:

void fn() {
final value = 'hello';

assert(value.isNotEmpty, 'Not Empty');

Widget(GlobalKey('label'));

StateError('Some State');
Exception('Some Exception');
RegExp('pattern');
Uri.https('https');

value.split(',');

const map = {'some': 'another'};
map['some'];
}