跳到主要內容

curly_braces_in_flow_control_structures

穩定
核心
提供修正

所有流程控制結構都**應該**使用大括號。

詳細資訊

#

應該 所有流程控制結構都使用大括號。

這樣做可以避免懸空的 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!');
}

這有一個例外:如果 if 陳述式沒有 else 子句,且整個 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