Rules / Complexity / prefer-conditional-assignment

prefer-conditional-assignment

lint/complexity/prefer-conditional-assignment
recommended
Same as prefer_conditional_assignment · Dart lints

Flags if (x == null) { x = y; } with no else branch.

A null-guarded assignment like this is exactly what the ??= compound operator expresses: x ??= y. The shorter form removes a branch and states the intent — assign only when currently null — directly. The rule matches an if with no else whose condition is an == null check and whose single then-statement assigns to that same operand.

Invalid

example.dartdart
void f(int? a, C obj) {
  if (a == null) { a = 0; }
  if (a == null) a = 1;
  if (null == a) { a = 2; }
  if (obj.field == null) { obj.field = 3; }
  if (obj.field == null) obj.field = 4;
  print('$a ${obj.field}');
}

class C {
  int? field;
}
Prefer using a conditional assignment '??='.
1void f(int? a, C obj) {
2 if (a == null) { a = 0; }
Prefer using a conditional assignment '??='.
2 if (a == null) { a = 0; }
3 if (a == null) a = 1;
Prefer using a conditional assignment '??='.
3 if (a == null) a = 1;
4 if (null == a) { a = 2; }
Prefer using a conditional assignment '??='.
4 if (null == a) { a = 2; }
5 if (obj.field == null) { obj.field = 3; }
Prefer using a conditional assignment '??='.
5 if (obj.field == null) { obj.field = 3; }
6 if (obj.field == null) obj.field = 4;

Valid

example.dartdart
void f(int? a, int? b, C obj) {
  if (a == null) {
    a = 0;
  } else {
    a = 1;
  }
  if (a == null) {
    b = 2;
  }
  if (a != null) {
    a = 3;
  }
  if (a == null) {
    print(a);
  }
  if (a == null) {
    a = 0;
    b = 1;
  }
  a ??= 5;
  print('$a $b ${obj.field}');
}

class C {
  int? field;
}

How to configure

Set the severity of prefer-conditional-assignment in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "complexity": {
        "prefer-conditional-assignment": "error"
      }
    }
  }
}