[英]What does an question (?) mark and dot (.) in dart language?
说我定义...
final DocumentSnapshot doc;
变量doc
可能为空,所以我使用问号和点...
print(widget.doc); // null
print(widget.doc == null); // true
print(widget.doc?.data['name']);
为什么widget.doc?.data['name']
抛出错误Tried calling: []("name")
widget.doc?.data['name']
Tried calling: []("name")
而不是返回null
?
对于我的理解?.
检查是否为null
,如果是,将返回null
在当前版本的 Dart (2.3) 中,空感知访问不会使调用链短路。
因此,如果a
为空, a?.bc
将抛出异常,因为它与(a != null ? ab : null).c
。
在您的情况下, widget.doc?.data['name']
与((e) { return e != null ? e.data : null; }(widget.doc))['name']
。
为了使您的代码工作,您需要引入一个变量。
var a = widget.doc?.data;
print(a == null ? null : a['name']);
注意:您可能对#36541感兴趣:Map 没有可识别空值的可链接“get”方法
要保护对可能为 null 的对象的属性或方法的访问,请在点 ( .
) 之前放置一个问号 ( ?
):
myObject?.someProperty
前面的代码等效于以下内容:
(myObject != null) ? myObject.someProperty : null
您可以链接 ? 的多种用途。 一起在一个表达式中:
myObject?.someProperty?.someMethod()
如果myObject
或myObject.someProperty
为 null,则前面的代码返回 null(并且从不调用someMethod()
)。
代码示例尝试使用条件属性访问来完成下面的代码片段。
// This method should return the uppercase version of `str`
// or null if `str` is null.
String upperCaseIt(String str) {
return str?.toUpperCase();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.