Skip to main content

avoid-default-tostring

effort: 4m
configurable
teams+

Warns when a class is the target of the toString() invocation, but does not implement toString.

The result of calling toString() on such classes is Instance of ... which is usually not expected.

⚙️ Config

Set ignore-enums (default is false) to ignore toString() calls on enum constants.

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-default-tostring:
ignore-enums: false

Example

❌ Bad:

void fn(SomeClass some) {
// LINT: The class does not implement 'toString' and will give no meaningful output.
// Try implementing 'toString' or replacing with another value.
some.toString();

// LINT: The class does not implement 'toString' and will give no meaningful output.
// Try implementing 'toString' or replacing with another value.
print('$some');

// LINT: The class does not implement 'toString' and will give no meaningful output.
// Try implementing 'toString' or replacing with another value.
[some].toString();
}

class SomeClass {}

✅ Good:

void fn(SomeClass some) {
some.toString();
print('$some');
}

class SomeClass {

String toString() => 'hi';
}

Additional Resources