Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-aware operator with Lists

Tags:

dart

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] 

How do I use the null-aware operator on the List getter?

This does not work:

list?[index] 

and this does not exist for List's in Dart.

list?.get(index) 

I want to achieve something like this:

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] 
like image 530
creativecreatorormaybenot Avatar asked May 13 '18 11:05

creativecreatorormaybenot


People also ask

What are null-aware operators?

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.

How many null-aware operator are in flutter?

Anytime you can write less code without sacrificing readability, you probably should. The three null-aware operators that Dart provides are ?. , ?? , and ??= .

How do you deal with null values in flutter?

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.


1 Answers

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 
like image 90
Günter Zöchbauer Avatar answered Sep 23 '22 02:09

Günter Zöchbauer