In Dart the null-aware operator for methods in combination with the ??
operator does not work well.
Image having a call chain like this:
object.getter.getter.getter.getter
Now when object
could be null and I do not want an exception I have to write this:
object?.getter?.getter?.getter?.getter
That is a null check for every getter, even though only object
can be null, but then the getter
's obviously do not work.
I am okay with this. But now I have a scenario, where I want to return another value if null, but I am working with a list:
list[index][index][index]
This does not work:
list?[index]
and this does not exist for List
's in Dart.
list?.get(index)
list?[index]?[index]?[index] ?? 0
Where I know that only list
will ever be null
.
This long code would work:
list == null ? 0 : list[index][index][index]
Null-aware operators are used in almost every programming language to check whether the given variable value is Null. The keyword for Null in the programming language Dart is null. Null means a variable which has no values assign ever and the variable is initialized with nothing like.
Anytime you can write less code without sacrificing readability, you probably should. The three null-aware operators that Dart provides are ?. , ?? , and ??= .
Use the fallback operator to set a default value for null values before using the variable. Here, "str" is null, and we set the fallback operator with fallback value in case of "str" is null. You need to do this before using it on the code.
There is no null-aware operator for the indexing operator ([]
)
You can use elementAt()
instead:
list?.elementAt(index)?.elementAt(index)?.elementAt(index) ?? 0
UPDATE - 2021/05/24
If you are using null-safety, you can now use this:
list?[index]?[index]?[index] ?? 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With