Rules / Suspicious / unnecessary-null-aware-assignments

unnecessary-null-aware-assignments

lint/suspicious/unnecessary-null-aware-assignments
recommended
Same as unnecessary_null_aware_assignments · Dart lints

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;
}
Unnecessary null-aware assignment to null.
1void f(int? a, C obj, Map<String, int> m) {
2 a ??= null;
Unnecessary null-aware assignment to null.
2 a ??= null;
3 obj.field ??= null;
Unnecessary null-aware assignment to null.
3 obj.field ??= null;
4 m['k'] ??= null;
Unnecessary null-aware assignment to null.
4 m['k'] ??= null;
5 _top ??= null;
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;
}

How to configure

Set the severity of unnecessary-null-aware-assignments in your falcon.json:

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