switch_on_type
避免对 'Type' 使用 switch 语句。
详情
#避免对 Type
使用 switch。
对 Type
使用 switch 不具备类型安全性,并且在类层次结构发生变化时可能导致 bug。建议改为对变量使用模式匹配。
错误示例
dart
void f(Object o) {
switch (o.runtimeType) {
case int:
print('int');
case String:
print('String');
}
}
正确示例
dart
void f(Object o) {
switch(o) {
case int():
print('int');
case String _:
print('String');
default:
print('other');
}
}
启用
#要启用 switch_on_type
规则,请将 switch_on_type
添加到你的 analysis_options.yaml
文件中 linter > rules 下方
analysis_options.yaml
yaml
linter:
rules:
- switch_on_type
如果你使用 YAML 映射语法配置 linter 规则,请在 linter > rules 下方添加 switch_on_type: true
analysis_options.yaml
yaml
linter:
rules:
switch_on_type: true