unnecessary-null-aware-assignments

Same as unnecessary_null_aware_assignments in Dart lints

Path
lint/suspicious/unnecessary-null-aware-assignments
Default
On (recommended)
Origin
Dart lints
Rule
462 of 512
recommended

Flags x ??= null, which can never have an effect.

The ??= operator assigns only when the target is currently null, so assigning null is a guaranteed no-op: a null target stays null, and otherwise nothing happens. Such a statement is dead code that usually points to a mistaken right-hand side — the author likely meant a real default value. Remove the statement, or supply the value that was intended.

Invalid

example.dartdart
void f(int? a, C obj, Map<String, int> m) {
  a ??= null;
  obj.field ??= null;
  m['k'] ??= null;
  _top ??= null;
  obj.nested.value ??= null;
  print('$a ${obj.field} $m');
}

int? _top;

class C {
  int? field;
  int? value;
  C get nested => this;
}
Remove this unnecessary null-aware assignment to `null`.
1void f(int? a, C obj, Map<String, int> m) {
2 a ??= null;
Remove this unnecessary null-aware assignment to `null`.
2 a ??= null;
3 obj.field ??= null;
Remove this unnecessary null-aware assignment to `null`.
3 obj.field ??= null;
4 m['k'] ??= null;
Remove this unnecessary null-aware assignment to `null`.
4 m['k'] ??= null;
5 _top ??= null;
Remove this unnecessary null-aware assignment to `null`.
5 _top ??= null;
6 obj.nested.value ??= null;

Valid

example.dartdart
void f(int? a, C obj) {
  a ??= 0;
  a ??= compute();
  a = null;
  obj.field ??= 5;
  a = (a ?? 0) + 1;
  print('$a ${obj.field}');
}

int compute() => 0;

class C {
  int? field;
}

Configure unnecessary-null-aware-assignments

Set its severity in falcon.json. See the configuration guide.

falcon.jsonjson
{
  "linter": {
    "rules": {
      "suspicious": {
        "unnecessary-null-aware-assignments": "error"
      }
    }
  }
}

Or silence one occurrence with a suppression comment; the reason is required.

example.dartdart
// falcon-ignore lint/suspicious/unnecessary-null-aware-assignments: <reason>