dart语言中的问号(?)和点号(。)是什么意思?

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") 而不是 returning null?

根据我的理解 ?. 检查是否 null 如果会 return null

在当前版本的 Dart (2.3) 中 Null-aware 访问 没有 short-circuit 调用链。

所以如果 a 为 null,a?.b.c 将抛出异常,因为它与 (a != null ? a.b : 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 does not have a null-aware-chainable "get" method

感兴趣

要保护对可能为空的对象的 属性 或方法的访问,请在点 (.) 前加上问号 (?):

myObject?.someProperty

上述代码等同于:

(myObject != null) ? myObject.someProperty : null

您可以链接多次使用 ?。放在一个表达式中:

myObject?.someProperty?.someMethod()

如果 myObjectmyObject.someProperty 为空,则前面的代码 returns 为空(并且从不调用 someMethod())。

代码示例 尝试使用条件 属性 访问来完成下面的代码片段。

// This method should return the uppercase version of `str`
// or null if `str` is null.
String upperCaseIt(String str) {
  return str?.toUpperCase();
}