no-magic-string
Warns when string 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. Additionally, this rule helps find places where string literals are used instead of localization strings.
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).
For this rule it's recommended to exclude the test
folder.
⚙️ Config
Set allow-only-once
(default is false
) to allow magic strings that are used one time within a file (example).
Set ignored-invocations
(default is [print
, debugPrint
]) to ignore strings in specific invocations (example).
dart_code_metrics:
rules:
- no-magic-string:
allow-only-once: false
ignored-invocations:
- print
- debugPrint
Example
❌ Bad:
void fn() {
final instance = SomeClass('something'); // LINT: Avoid magic strings. Try extracting them to named constants or variables.
if (instance.value == 'another') {} // LINT: Avoid magic strings. Try extracting them to named constants or variables.
instance.work('work'); // LINT: Avoid magic strings. Try extracting them to named constants or variables.
}
✅ 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'];
}
Example with "allow-only-once"
Config
dart_code_metrics:
rules:
- no-magic-string:
allow-only-once: true
✅ Good:
void fn() {
final instance = SomeClass('something'); // Correct, used only once
}
Example with "ignored-invocations"
Config
dart_code_metrics:
rules:
- no-magic-string:
ignored-invocations:
- print
✅ Good:
void fn() {
print('something'); // Correct, 'print' is ignored
}