Null-aware operator with Lists

2019-06-27 01:07发布

问题:

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]

回答1:

There is no null-aware operator for the indexing operator ([])

You can use elementAt() instead:

list?.elementAt(index)?.elementAt(index)?.elementAt(index) ?? 0


标签: dart