Contents
Contents

Avoid calling toString() on runtimeType.

This rule is available as of Dart 2.8.1.

Details

#

Calling toString on a runtime type is a non-trivial operation that can negatively impact performance. It's better to avoid it.

BAD:

dart
class A {
  String toString() => '$runtimeType()';
}

GOOD:

dart
class A {
  String toString() => 'A()';
}

This lint has some exceptions where performance is not a problem or where real type information is more important than performance:

  • in an assertion
  • in a throw expression
  • in a catch clause
  • in a mixin declaration
  • in an abstract class declaration

Usage

#

To enable the no_runtimeType_toString rule, add no_runtimeType_toString under linter > rules in your analysis_options.yaml file:

analysis_options.yaml
yaml
linter:
  rules:
    - no_runtimeType_toString