跳到主要內容

流控制結構中的花括號

穩定
核心
有修復可用

應為所有流控制結構使用花括號。

詳情

#

為所有流控制結構使用花括號。

這樣做可以避免懸空 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