null_closures
不要在期望使用閉包作為引數的地方傳遞 null。
詳情
#不要 在期望使用閉包作為引數的地方傳遞 null。
傳遞給方法的閉包通常只會根據條件呼叫,因此測試和“正常路徑”生產呼叫可能不會發現傳遞 null 會導致丟擲異常。
此規則僅捕獲在以下位置期望使用閉包時傳遞的 null 字面量
建構函式
#- 來自
dart:asyncFuture的第 0 個位置引數Future.microtask的第 0 個位置引數Future.sync的第 0 個位置引數Timer的第 0 個位置引數Timer.periodic的第 1 個位置引數
- 來自
dart:coreList.generate的第 1 個位置引數
靜態函式
#- 來自
dart:asyncscheduleMicrotask的第 0 個位置引數Future.doWhile的第 0 個位置引數Future.forEach的第 0 個位置引數Future.wait的命名引數cleanupTimer.run的第 0 個位置引數
例項方法
#- 來自
dart:asyncFuture.then的第 0 個位置引數Future.complete的第 0 個位置引數
- 來自
dart:collectionQueue.removeWhere的第 0 個位置引數Queue.retainIterable.firstWhere的第 0 個位置引數和命名引數orElseIterable.forEach的第 0 個位置引數Iterable.fold的第 1 個位置引數Iterable.lastWhere的第 0 個位置引數和命名引數orElseIterable.map的第 0 個位置引數Iterable.reduce的第 0 個位置引數Iterable.singleWhere的第 0 個位置引數和命名引數orElseIterable.skipWhile的第 0 個位置引數Iterable.takeWhile的第 0 個位置引數Iterable.where的第 0 個位置引數List.removeWhere的第 0 個位置引數List.retainWhere的第 0 個位置引數String.replaceAllMapped的第 1 個位置引數String.replaceFirstMapped的第 1 個位置引數String.splitMapJoin的命名引數onMatch和onNonMatch
不良示例
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 對映語法配置 linter 規則,請在 linter > rules 下新增 null_closures: true
analysis_options.yaml
yaml
linter:
rules:
null_closures: true