unnecessary_breaks
当 break 是隐含的时候,不要使用显式的 break
。
详情
#仅当需要在 case 代码块结束之前跳出时,才在非空的 switch case 语句中使用 break
。Dart 不支持非空 case 的 fallthrough 执行,因此在非空 switch case 语句末尾的 break
是不必要的。
错误示例
dart
switch (1) {
case 1:
print("one");
break;
case 2:
print("two");
break;
}
正确示例
dart
switch (1) {
case 1:
print("one");
case 2:
print("two");
}
dart
switch (1) {
case 1:
case 2:
print("one or two");
}
dart
switch (1) {
case 1:
break;
case 2:
print("just two");
}
注意:此 lint 仅报告语言版本为 3.0 或更高版本的库中不必要的 break。在 Dart 2.19 及更低版本中,仍然需要显式的 break。
启用
#要启用 unnecessary_breaks
规则,请在你的 analysis_options.yaml
文件中的 linter > rules 下添加 unnecessary_breaks
analysis_options.yaml
yaml
linter:
rules:
- unnecessary_breaks
如果您改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 unnecessary_breaks: true
analysis_options.yaml
yaml
linter:
rules:
unnecessary_breaks: true
除非另有说明,否则本网站上的文档反映了 Dart 3.7.1 版本。页面上次更新于 2025-03-07。 查看源代码 或 报告问题。