目录

avoid_type_to_string

目录

Avoid .toString() in production code since results may be minified.

This rule is available as of Dart 2.12.

Details

#

DO avoid calls to .toString() in production code, since it does not contractually return the user-defined name of the Type (or underlying class). Development-mode compilers where code size is not a concern use the full name, but release-mode compilers often choose to minify these symbols.

BAD:

dart
void bar(Object other) {
  if (other.runtimeType.toString() == 'Bar') {
    doThing();
  }
}

Object baz(Thing myThing) {
  return getThingFromDatabase(key: myThing.runtimeType.toString());
}

GOOD:

dart
void bar(Object other) {
  if (other is Bar) {
    doThing();
  }
}

class Thing {
  String get thingTypeKey => ...
}

Object baz(Thing myThing) {
  return getThingFromDatabase(key: myThing.thingTypeKey);
}

Usage

#

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

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_type_to_string