prefer_conditional_assignment
The 'if' statement could be replaced by a null-aware assignment.
Description
#The analyzer produces this diagnostic when an assignment to a variable is conditional based on whether the variable has the value null
and the ??=
operator could be used instead.
Example
#The following code produces this diagnostic because the parameter s
is being compared to null
in order to determine whether to assign a different value:
dart
int f(String? s) {
if (s == null) {
s = '';
}
return s.length;
}
Common fixes
#Use the ??=
operator instead of an explicit if
statement:
dart
int f(String? s) {
s ??= '';
return s.length;
}
Was this page's content helpful?
Thank you for your feedback!
Provide details Thank you for your feedback! Please let us know what we can do to improve.
Provide details Unless stated otherwise, the documentation on this site reflects Dart 3.8.1. Page last updated on 2025-05-08. View source or report an issue.