跳到主要内容

流控制结构中的花括号

稳定
核心
有修复可用

应为所有流控制结构使用花括号。

详情

#

为所有流控制结构使用花括号。

这样做可以避免悬空 else 问题。

错误示例

dart
if (overflowChars != other.overflowChars)
  return overflowChars < other.overflowChars;

正确示例

dart
if (isWeekDay) {
  print('Bike to work!');
} else {
  print('Go dancing or read a book!');
}

有一个例外:不带 else 子句的 if 语句,且整个 if 语句(包括条件和主体)可以放在一行。在这种情况下,如果愿意,可以省略花括号

正确示例

dart
if (arg == null) return defaultValue;

但是,如果主体换行到下一行,则应使用花括号

正确示例

dart
if (overflowChars != other.overflowChars) {
  return overflowChars < other.overflowChars;
}

启用

#

要启用 curly_braces_in_flow_control_structures 规则,请在你的 analysis_options.yaml 文件中的 linter > rules 下添加 curly_braces_in_flow_control_structures

analysis_options.yaml
yaml
linter:
  rules:
    - curly_braces_in_flow_control_structures

如果你使用 YAML map 语法配置 linter 规则,请在 linter > rules 下添加 curly_braces_in_flow_control_structures: true

analysis_options.yaml
yaml
linter:
  rules:
    curly_braces_in_flow_control_structures: true