简体   繁体   English

在 Dart 语言中,问号 (?) 标记和点 (.) 是什么意思?

[英]What does an question (?) mark and dot (.) in dart language?

say I defined ...说我定义...

final DocumentSnapshot doc;

variable doc might be null so I use a question mark and dot...变量doc可能为空,所以我使用问号和点...

print(widget.doc); // null
print(widget.doc == null); // true
print(widget.doc?.data['name']);

why widget.doc?.data['name'] throw error Tried calling: []("name") instead returning null ?为什么widget.doc?.data['name']抛出错误Tried calling: []("name") widget.doc?.data['name'] Tried calling: []("name")而不是返回null

for my understanding ?.对于我的理解?. to check whether null and if it so will return null检查是否为null ,如果是,将返回null

In the current version of Dart (2.3) Null-aware access doesn't short-circuit call chain.在当前版本的 Dart (2.3) 中,空感知访问不会使调用链短路。

So a?.bc will throw an exception if a is null because it's the same as (a != null ? ab : null).c .因此,如果a为空, a?.bc将抛出异常,因为它与(a != null ? ab : null).c

In your case widget.doc?.data['name'] is the same as ((e) { return e != null ? e.data : null; }(widget.doc))['name'] .在您的情况下, widget.doc?.data['name']((e) { return e != null ? e.data : null; }(widget.doc))['name']

To make your code working you need to introduce a variable.为了使您的代码工作,您需要引入一个变量。

var a = widget.doc?.data;
print(a == null ? null : a['name']);

NB: you may be interested by #36541: Map does not have a null-aware-chainable "get" method注意:您可能对#36541感兴趣:Map 没有识别空值的可链接“get”方法

To guard access to a property or method of an object that might be null, put a question mark ( ? ) before the dot ( . ):要保护对可能为 null 的对象的属性或方法的访问,请在点 ( . ) 之前放置一个问号 ( ? ):

myObject?.someProperty

The preceding code is equivalent to the following:前面的代码等效于以下内容:

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

You can chain multiple uses of ?.您可以链接 ? 的多种用途。 together in a single expression:一起在一个表达式中:

myObject?.someProperty?.someMethod()

The preceding code returns null (and never calls someMethod() ) if either myObject or myObject.someProperty is null.如果myObjectmyObject.someProperty为 null,则前面的代码返回 null(并且从不调用someMethod() )。

Code example Try using conditional property access to finish the code snippet below.代码示例尝试使用条件属性访问来完成下面的代码片段。

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM