So I've been following along to a fireship course on dart and I got the error: "Null check operator used on a null value". Was just wondering why? Here is the code:
String? answer;
String result = answer!;
CodePudding user response:
That's working exactly as intended.
The String? answer;
declaration introduces a nullable variable with a current value of null
.
The answer!
expression reads that value, checks whether it's null
, throws if the value is null
, or evaluates to the non-null
value if it isn't null
.
Since the value is indeed null
, that operation throws the error you see.
The !
is the "null check operator". It's used on the value null
. The error message is actually quite precise.
To avoid that, make sure the answer
variable has a non-null
value when you use the !
operator on it. (Often you won't need the !
for local variables because assigning a non-null
value to the variable also promotes the variable's type to non-nullable, but there are cases where the compiler can't see that assignment, for example if it happens in a callback function.)