簡體   English   中英

在 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") 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()

如果myObjectmyObject.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM