跳到主要内容

avoid_type_to_string

稳定版

避免在生产代码中使用 .toString(),因为结果可能会被精简。

详情

#

避免在生产代码中调用.toString(),因为它并未约定返回 Type(或底层类)的用户定义名称。开发模式编译器不关注代码大小,会使用完整名称,但发布模式编译器通常会精简这些符号。

不推荐

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

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

推荐

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

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

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

启用

#

要在您的 analysis_options.yaml 文件中启用 avoid_type_to_string 规则,请在 linter > rules 下添加 avoid_type_to_string

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_type_to_string

如果您使用 YAML 映射语法来配置 Linter 规则,请在 linter > rules 下添加 avoid_type_to_string: true

analysis_options.yaml
yaml
linter:
  rules:
    avoid_type_to_string: true