Skip to main content

prefer-null-aware-elements

effort: 2m
dart 3.8+
configurable
teams+

Suggests using null-aware elements (?element) instead of checking for a potential null value.

⚙️ Config

Set ignore-nullable-chains (default is true) to ignore chained nullable property accesses or method invocations (e.g. instance?.prop?.another) (example). Using null-aware elements in such cases can change the meaning of the code.

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-null-aware-elements:
ignore-nullable-chains: true

Example

❌ Bad:

void fn(int? x, Some? input) {
final map = {
// LINT: Prefer null-aware elements (?element) instead of checking for a potential null value.
if (x != null) "key1": x,

// LINT: Prefer null-aware elements (?element) instead of checking for a potential null value.
if (x != null) x: "",

// LINT: Prefer null-aware elements (?element) instead of checking for a potential null value.
if (x != null) x: x,

// LINT: Prefer null-aware elements (?element) instead of checking for a potential null value.
if (input != null) "key": input.value,

// LINT: Prefer null-aware elements (?element) instead of checking for a potential null value.
if (input != null) input.value: "value",
};

final list = [
// LINT: Prefer null-aware elements (?element) instead of checking for a potential null value.
if (input != null) input,

// LINT: Prefer null-aware elements (?element) instead of checking for a potential null value.
if (input != null) input.value,
];
}

✅ Good:

void fn(int? x, Some? input) {
final map = {
"key1": ?x,
?x: "",
?x: x,

"key": ?input.value,
?input.value: "value",
};

final list = [
?input,
?input.value,
];
}

Example with "ignore-nullable-chains"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-null-aware-elements:
ignore-nullable-chains: false

❌ Bad:

void fn(Some? input) {
final list = [
// LINT: Prefer null-aware elements (?element) instead of checking for a potential null value.
if (input != null) input.another, // both `input` and `another` are nullable
];
}

class Some {
int? another;
}