跳到主要内容

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 {}