跳到主要內容

avoid_type_to_string

Stable

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

詳細資訊

#

務必 避免呼叫.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.

錯誤範例

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);
}

啟用

#

若要啟用 avoid_type_to_string 規則,請在您的 analysis_options.yaml 檔案中的 linter > rules 下新增 avoid_type_to_string

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_type_to_string

如果您改用 YAML map 語法來設定 linter 規則,請在 linter > rules 下新增 avoid_type_to_string: true

analysis_options.yaml
yaml
linter:
  rules:
    avoid_type_to_string: true