Very simple and "nooby" question but what does ! do in dart?
Here is an example:
File? _selectedFile;
Widget joe() {
if (_selectedFile != null) {
return Image.file(
_selectedFile!, // can't do _selectedFile?
width: 250,
height: 250,
fit: BoxFit.cover,
);
}
return Text("mama");
}
I know that the ?
in File? _selectedFile
means that _selectedFile is allowed to be null. But when I do _selectedFile?
in the Widget function, it throws errors but when I do _selectedFile!
, it works. Why is that so?
CodePudding user response:
The exclamation mark is a dangerous but powerful operator.
It tells the compiler to assume the value is not null.
When you do this, the type gets cast from a nullable to a non-nullable type, and can be used in places that accept only non-nullable values.
When you do this, you must entirely trust your code not to accidentally use a null value.
More information in this question/answer.
In your specific situation, we can be sure that the value is not null because of your if statement that checks this.
Because of this, I would imagine you can just use _selectedFile
without any additional operator. When you do this, you force the compiler to prove the safety of your code, rather than you just trusting yourself. If the compiler is satisfied, the code will compile. I haven't used Dart, so I don't know how smart the compiler is, but hopefully it can handle this circumstance without requiring you to take a risk with the !
operator.
CodePudding user response:
in the new versions of dart that supports null safety :
in your code
?
: means that _selectedFile
can be null
if you added !
after _selectedFile
that means that you are telling the compiler the opposite of what you have already declared it , !
is used to make the compiler knows that _selectedFile
is never null ! see what you are doing here ?
!=
means "if not"