[英]Flutter/Dart - Difference between obj!.property and obj?.property
In Flutter/Dart their is the null safety feature.在 Flutter/Dart 中,它们是 null 安全功能。 In my scenario, I have null safety ON and I am trying to get the property 'myDateTime' of my object MyDateTime.
在我的场景中,我打开了 null 安全,我正在尝试获取我的 object MyDateTime 的属性“myDateTime”。 But the compiler produce the error:
但是编译器会产生错误:
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 ('!').
which makes sense because the object can be null.这是有道理的,因为 object 可以是 null。
I tried both solution我尝试了两种解决方案
MyDateTime!.myDateTime
and和
MyDateTime?.myDateTime
and the both work fine but I don't understand the difference?!两者都可以正常工作,但我不明白其中的区别?! Can anyone elaborate?
谁能详细说明?
MyDateTime..myDateTime
means: i know MyDateTime
can never be null and it tries to access property myDateTime
even if MyDateTime
is null. MyDateTime..myDateTime
的意思是:我知道MyDateTime
永远不可能是 null,即使MyDateTime
是 null,它也会尝试访问属性myDateTime
。
MyDateTime?.myDateTime
means: i know MyDateTime
can be null, so if it is, don't try to access property myDateTime
MyDateTime?.myDateTime
表示:我知道MyDateTime
可以是 null,所以如果是,请不要尝试访问属性myDateTime
The first one returns an error if MyDateTime
is null, the other one does not.如果
MyDateTime
为 null,则第一个返回错误,另一个则不返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.