目錄

null_closures

當需要閉包時,請勿將 null 作為引數傳遞。

此規則從 Dart 2.0 開始可用。

規則集:建議flutter

此規則有快速修正可用。

詳細資訊

#

不要null 作為引數傳遞,當需要閉包時。

通常,傳遞給方法的閉包只會在有條件的情況下呼叫,因此測試和「正常路徑」的生產呼叫不會揭露 null 會導致擲回例外。

此規則僅捕獲在以下位置中,預期閉包時傳遞的 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.retainWhere 在第 0 個位置引數
    • 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