目錄

avoid_type_to_string

避免在正式程式碼中使用 .toString(),因為結果可能會被縮減。

此規則自 Dart 2.12 起可用。

詳細資訊

#

應該避免在正式程式碼中呼叫.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);
}

用法

#

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

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_type_to_string