60 lines
1.8 KiB
Plaintext
60 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Nullability of types is an important part of Dart's type system. In order to simplify the work with nullable types in the Dart language there are many null-aware operators (`??`, `??=`, `?.`, `!`, `?..`, `?[]`, ``++...?++``). Using those operators will make your code more clear and concise.
|
|
|
|
The If-null operator (`??`), will check if the value on the left side is `null`, and, if yes, will return the expression on the right. This is an easy way to set default values instead of dealing with `null`. Thus, this operator doesn't make sense if used with `null` on either sides.
|
|
|
|
For example, in `null ?? x` the `x` will always be returned. Using the operator here only introduces confusion and additional cognitive load. In case of `x ?? null`, again the result will always be the value of `x`. In both cases the operator can be replaced with just `x`.
|
|
|
|
== How to fix it
|
|
|
|
Depending on your context, remove the `null ??` / `null ??` part, or replace `null` with some meaningful value.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,dart,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
void f(String? s) {
|
|
var myString1 = s ?? null;
|
|
var myString2 = null ?? s;
|
|
var myString3 = s ?? null;
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,dart,diff-id=1,diff-type=compliant]
|
|
----
|
|
void f(String? s) {
|
|
var my_string1 = s;
|
|
var my_string2 = s;
|
|
var my_string3 = s ?? "default";
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* Dart Docs - https://dart.dev/tools/linter-rules/unnecessary_null_in_if_null_operators[Dart Linter rule - unnecessary_null_in_if_null_operators]
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Unnecessary use of '??' with 'null'.
|
|
|
|
=== Highlighting
|
|
|
|
Only `null` keyword
|
|
|
|
endif::env-github,rspecator-view[]
|
|
|