0

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....

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);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
John Han
  • 31
  • 6

2 Answers2

1

The meaning of your code snippet A is:

If the image variable is null it will return null otherwise it will return the image variable.

The meaning of your code snippet B is:

It returns the image variable, although the image variable may be null.

If you use code snippet B, you use ! 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.

My Car
  • 4,198
  • 5
  • 17
  • 50
0

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 ! on nullable value which is wrong.

If you look for short form you can try this:

return image == null ? null : File(image.path);
My Car
  • 4,198
  • 5
  • 17
  • 50
eamirho3ein
  • 16,619
  • 2
  • 12
  • 23