跳到主要內容

avoid_type_to_string

在生產程式碼中對 'Type' 使用 'toString' 是不安全的。

描述

#

當對一個靜態型別為 Type 的值呼叫 toString 方法時,分析器會生成此診斷資訊。

示例

#

以下程式碼會生成此診斷資訊,因為它對 runtimeType 返回的 Type 呼叫了 toString 方法

dart
bool isC(Object o) => o.runtimeType.toString() == 'C';

class C {}

常見修復方法

#

如果型別必須完全相同,請使用顯式比較

dart
bool isC(Object o) => o.runtimeType == C;

class C {}

如果該型別的子型別例項返回 true 也可以接受,請使用型別檢查

dart
bool isC(Object o) => o is C;

class C {}