Skip to content

ambiguous_if_null_grouping

Reports a ?? that groups differently from how the line reads. Add the parentheses you mean.

Tier
advisory
Scope
Dart
Lowest preset
strict
Fix
write the parentheses of the grouping in effect

A ?? without parentheses, in two cases:

  • A cascade on it: cached ?? Builder()..add(item) is (cached ?? Builder())..add(item). It adds to cached as well, though it reads as if only the new builder were changed.
  • An arithmetic, shift or bitwise operation after it: count ?? 0 + 1 is count ?? (0 + 1), and adds nothing to count. Such an operation gives a value of the type of its operands, so the grouping the line suggests, (count ?? 0) + 1, would compile as well.

It does not report:

  • a chain of ??, a ?? b ?? c, which reads as it binds;
  • an operand in parentheses: a ?? (b + 1), (a ?? b) + 1;
  • an operation on the left of ??: a + b ?? c;
  • a comparison, a logical operator, is or as after ??, such as enabled ?? mode == Mode.on. These give a bool or another type than the operands, so the other grouping would not give the same kind of value.

?? binds more loosely than the operators beside it, and most readers expect otherwise. So count ?? 0 + 1 reads as one more than the count, but it is the count, or one where there is none. A cascade after ?? changes an object the line does not seem to touch.

The code does exactly what the grammar says. That is why the rule is advisory and in strict only: it is about reading, not a defect of its own.

Violating
int next(int? last) => last ?? 0 + 1;
List<String> withDefault(List<String>? names) => names ?? []..add('guest');
Correctedby writing what was meant
int next(int? last) => (last ?? 0) + 1;
List<String> withDefault(List<String>? names) => names ?? (<String>[]..add('guest'));

The fix writes the parentheses of the grouping in effect, so nothing that runs changes: count ?? 0 + 1 becomes count ?? (0 + 1), and cached ?? Builder()..add(item) becomes (cached ?? Builder())..add(item). The rule cannot know which grouping you meant. If you meant the other one, as in the example above, move the parentheses by hand.

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.
assay:
rules:
ambiguous_if_null_grouping:
exclude: ["lib/generated/**"]

Write why on the line directly above the suppression:

// The fallback is one more than none, as the format counts from one.
// ignore: assay/ambiguous_if_null_grouping

// ignore_for_file: assay/ambiguous_if_null_grouping silences it in a whole file, and // ignore: ambiguous_if_null_grouping without the prefix works too. See Suppressions.