跳到主要內容

null_closures

穩定
推薦
提供修復

請勿在預期 Closure 的地方傳遞 null 作為引數。

詳細資訊

#

請「不要」在預期 Closure 的地方傳遞 null 作為引數。

通常傳遞給方法的 Closure 只會在特定條件下呼叫,因此測試和「正常路徑」的生產呼叫不會揭露 null 會導致例外拋出。

此規則僅捕捉在以下位置,當預期 Closure 時傳遞 null 字面值的情況

建構子

#
  • 來自 dart:async
    • Future 在第 0 個位置參數
    • Future.microtask 在第 0 個位置參數
    • Future.sync 在第 0 個位置參數
    • Timer 在第 0 個位置參數
    • Timer.periodic 在第 1 個位置參數
  • 來自 dart:core
    • List.generate 在第 1 個位置參數

靜態函式

#
  • 來自 dart:async
    • scheduleMicrotask 在第 0 個位置參數
    • Future.doWhile 在第 0 個位置參數
    • Future.forEach 在第 0 個位置參數
    • Future.wait 在名為 cleanup 的參數
    • Timer.run 在第 0 個位置參數

實例方法

#
  • 來自 dart:async
    • Future.then 在第 0 個位置參數
    • Future.complete 在第 0 個位置參數
  • 來自 dart:collection
    • Queue.removeWhere 在第 0 個位置參數
    • `Queue.retain
    • Iterable.firstWhere 在第 0 個位置參數,以及名為 orElse 的參數
    • Iterable.forEach 在第 0 個位置參數
    • Iterable.fold 在第 1 個位置參數
    • Iterable.lastWhere 在第 0 個位置參數,以及名為 orElse 的參數
    • Iterable.map 在第 0 個位置參數
    • Iterable.reduce 在第 0 個位置參數
    • Iterable.singleWhere 在第 0 個位置參數,以及名為 orElse 的參數
    • Iterable.skipWhile 在第 0 個位置參數
    • Iterable.takeWhile 在第 0 個位置參數
    • Iterable.where 在第 0 個位置參數
    • List.removeWhere 在第 0 個位置參數
    • List.retainWhere 在第 0 個位置參數
    • String.replaceAllMapped 在第 1 個位置參數
    • String.replaceFirstMapped 在第 1 個位置參數
    • String.splitMapJoin 在名為 onMatchonNonMatch 的參數

錯誤範例

dart
[1, 3, 5].firstWhere((e) => e.isOdd, orElse: null);

正確範例

dart
[1, 3, 5].firstWhere((e) => e.isOdd, orElse: () => null);

啟用

#

若要啟用 null_closures 規則,請在您的 analysis_options.yaml 檔案中的 linter > rules 下新增 null_closures

analysis_options.yaml
yaml
linter:
  rules:
    - null_closures

如果您改用 YAML map 語法來設定 linter 規則,請在 linter > rules 下新增 null_closures: true

analysis_options.yaml
yaml
linter:
  rules:
    null_closures: true