跳至主内容

null_closures

稳定
推荐
有可用修复

不要在期望使用闭包作为参数的地方传递 null

详情

#

不要 在期望使用闭包作为参数的地方传递 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.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 映射语法配置 linter 规则,请在 linter > rules 下添加 null_closures: true

analysis_options.yaml
yaml
linter:
  rules:
    null_closures: true