Skip to content

null_guarded_spread

Reports a collection element that spreads a value only where it is not null. Write ...?value instead.

Tier
advisory
Scope
Dart
Lowest preset
recommended
Fix
writes ...?value

An element of a list, set or map literal like [if (extra != null) ...extra], with or without a ! after the spread value, and with null != extra alike. The violation covers the if element.

It does not report:

  • an if with an else, or an if-case;
  • a test of more than null: extra != null && extra.isNotEmpty;
  • a spread of another value than the one tested;
  • a value that is not repeatable, such as widget.items: a getter written in the source or a call may give another value the second time, which the single read of ...? would not see.

The fix writes ...?extra. It is not offered where a comment stands in the element.

From Dart 3.12 on, the SDK lint use_null_aware_elements reports such a spread too, where the project switches it on, as recommended and strict do. So that one defect is one violation, this rule then leaves the places the lint reports to it, in both hosts. That holds where the lint is on and not set to ignore under analyzer.errors. The lint reports the place at the if, as an info, the same tier as this rule.

The lint reports, in a library whose language version has null-aware elements (3.8 and later):

  • a local variable or parameter spread by its bare name: if (extra != null) ...extra, with null on either side and the test in brackets alike;
  • a getter, fields included, spread by its bare name with a !: if (names != null) ...names!.

This rule keeps reporting, on every SDK, the forms the lint leaves out:

  • a ! after a local variable or parameter: ...extra!;
  • a spread value in brackets: ...(extra);
  • a value after this. or another prefix;
  • a private field that the test promotes: if (_tags != null) ..._tags;
  • every form in a library of an earlier language version.

The lint also reports an if-case (if (extra case final list?) ...list), which this rule does not. Where a place is left to the lint, assay fix does not apply this rule’s fix there.

The null-aware spread adds nothing for null and the elements of any other value, as the test and the spread do, and reads the value only once.

Violating
List<int> all(List<int>? extra) => [1, if (extra != null) ...extra];
Corrected
List<int> all(List<int>? extra) => [1, ...?extra];

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// Why it stays as written here.
// ignore: null_guarded_spread

// ignore_for_file: assay/null_guarded_spread silences it in a whole file, and the prefixed // ignore: assay/null_guarded_spread works too. See Suppressions.