跳到主要內容

no_runtimeType_toString

穩定版本

避免在 runtimeType 上呼叫 toString()

詳細資訊

#

在 runtime type 上呼叫 toString 是一個非輕量級的操作,可能會對效能產生負面影響。最好避免這樣做。

不良範例

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

良好範例

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

此 Lint 規則在某些效能不是問題,或真實類型資訊比效能更重要的情況下有一些例外

  • 在斷言中
  • 在 throw 表達式中
  • 在 catch 子句中
  • 在 mixin 宣告中
  • 在抽象類別宣告中

啟用

#

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

analysis_options.yaml
yaml
linter:
  rules:
    - no_runtimeType_toString

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

analysis_options.yaml
yaml
linter:
  rules:
    no_runtimeType_toString: true