簡體   English   中英

Flutter/Dart - obj.?property 和 obj..property 之間的區別

[英]Flutter/Dart - Difference between obj!.property and obj?.property

在 Flutter/Dart 中,它們是 null 安全功能。 在我的場景中,我打開了 null 安全,我正在嘗試獲取我的 object MyDateTime 的屬性“myDateTime”。 但是編譯器會產生錯誤:

The property 'myDateTime' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').

這是有道理的,因為 object 可以是 null。

我嘗試了兩種解決方案

MyDateTime!.myDateTime 

MyDateTime?.myDateTime 

兩者都可以正常工作,但我不明白其中的區別?! 誰能詳細說明?

MyDateTime..myDateTime的意思是:我知道MyDateTime永遠不可能是 null,即使MyDateTime是 null,它也會嘗試訪問屬性myDateTime

MyDateTime?.myDateTime表示:我知道MyDateTime可以是 null,所以如果是,請不要嘗試訪問屬性myDateTime

如果MyDateTime為 null,則第一個返回錯誤,另一個則不返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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