[英]Flutter, dart: what's the difference between these snippets of code?
Code snippet A is working, but not snippet B. I check variable "image"s data type with print(), both A and B's image (variable) has a datatype (XFile), not a Null. But B is still not working....代码片段 A 有效,但片段 B 无效。我用 print() 检查变量“图像”的数据类型,A 和 B 的图像(变量)都具有数据类型(XFile),而不是 Null。但 B 仍然无效....
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
print(image);
// Code snippet A
if (image == null) return null;
return File(image.path);
// Code snippet B
return File(image!.path);
The meaning of your code snippet A is:您的代码片段 A 的含义是:
If the image
variable is null it will return null otherwise it will return the image
variable.如果
image
变量是 null 它将返回 null 否则它将返回image
变量。
The meaning of your code snippet B is:您的代码片段 B 的含义是:
It returns the image
variable, although the image
variable may be null.它返回
image
变量,尽管image
变量可能是 null。
If you use code snippet B, you use !
如果您使用代码片段 B,则使用
!
and change the variable from a nullable type to a non-nullable type, and the variable is actually empty (has no value) and you can't use .path
so it returns an error.并将变量从可空类型更改为不可空类型,并且该变量实际上是空的(没有值)并且您不能使用
.path
因此它返回错误。
image
can be null
, In Code A
you check for nullable
value so you won't get exception
, but in code B
you are using !
image
可以是null
,在代码A
中,您检查可为nullable
的值,这样您就不会得到exception
,但在代码B
中,您正在使用!
on nullable
value which is wrong.在错误的
nullable
值上。
If you look for short form you can try this:如果你寻找简短的形式,你可以试试这个:
return image == null ? null : File(image.path);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.