【问题标题】:What does an question (?) mark and dot (.) in dart language?Dart 语言中的问号 (?) 和点 (.) 是什么?
【发布时间】:2019-10-06 22:52:00
【问题描述】:

说我定义了...

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") 而不是返回null

根据我的理解?. 检查是否null,如果是则返回null

【问题讨论】:

  • 会不会是doc != nulldata 是?在这种情况下,operator[] 将在 null 对象上调用。否则,您会很好地理解什么是 null 感知运算符。
  • 在 Alexandre 提到的 github 问题上删除一个 updoot。我们找到了它发生的原因,他告诉我们它是如何发生的。 O_o

标签: flutter dart null optional


【解决方案1】:

在当前版本的 Dart (2.3) Null-aware access 不会短路调用链。

所以如果a 为空,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感兴趣

【讨论】:

【解决方案2】:

要保护对可能为 null 的对象的属性或方法的访问,请在点 (.) 之前放置一个问号 (?):

myObject?.someProperty

前面的代码等价于:

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

您可以将 ? 的多种用途链接起来。放在一个表达式中:

myObject?.someProperty?.someMethod()

如果myObjectmyObject.someProperty 为null,则上述代码返回null(并且从不调用someMethod())。

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

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

【讨论】:

    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 2020-07-07
    • 2011-03-23
    • 2019-05-02
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多