Skip to content

recursive_to_string

Reports a toString that makes text of the object itself, which calls the same toString again without end. Write the fields, or super.toString().

Tier
blocking
Scope
Dart
Lowest preset
recommended
Fix
none

A place in the toString of a class, mixin or enum that makes text of the object itself:

  • '$this' or '${this}';
  • this.toString(), or toString() without a receiver;
  • buffer.write(this) or writeln(this) on a StringSink such as a StringBuffer.

The violation covers the expression.

It does not report:

  • code in a closure in the body, which may run where the object is made text otherwise;
  • super.toString(), the inherited text;
  • the toString of an extension or extension type, where this is made text by the toString of the value it extends.

The object works fine until it is printed. Then the first log line, error report or debugger view that shows it overflows the stack, often far from the toString. It is most often a “show everything” toString that meant super.toString() or the fields.

Violating
@override
String toString() => 'Point($this)';
Corrected
@override
String toString() => 'Point($x, $y)';

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// The test of the overflow needs it.
// ignore: recursive_to_string
String toString() => '$this';

// ignore_for_file: assay/recursive_to_string silences it in a whole file, and the prefixed // ignore: assay/recursive_to_string works too. See Suppressions.