具有列表的空感知运算符 [英] Null-aware operator with Lists

查看:57
本文介绍了具有列表的空感知运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dart 中,与 ?? 运算符结合使用的 null-aware 运算符不能很好地工作。

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

即使每个 object 可以为空,但是 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.

我对此很好。但是现在我有一个场景,我想在返回null时返回另一个值,但是我正在使用一个列表:

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]



如何在列表上使用空值运算符



这不起作用:

list?[index]

List则不存在 Dart 中。

list?.get(index)



我想要实现以下目标:



I want to achieve something like this:

list?[index]?[index]?[index] ?? 0

我知道只有 list 永远是 null

long 代码将起作用:

list == null ? 0 : list[index][index][index]


推荐答案

索引运算符( [] )没有空感知运算符

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

您可以使用 elementAt()代替:

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

这篇关于具有列表的空感知运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆