Reputation: 386
I am learning Dart and practicing with this video I came across this way of assigning a value when the variable is null
void main() {
int linus;
linus ??= 100;
print(linus);
}
When trying to test the code in VSCode I get the following error which I cannot identify its origin since from what I understand, I am using what is indicated in the documentation (and the video tutorial).
The non-nullable local variable 'linus' must be assigned before it can be used. Try giving it an initializer expression, or ensure that it's assigned on every execution path.
Upvotes: 1
Views: 860
Reputation: 26
The Dart Language now supports a new feature called sound null safety. Variables now are non-nullable by default meaning that you can not assign a null value to a variable unless you explicitly declare they can contain a null.
To indicate that a variable might have the value null, just add ? to its type declaration:
int? linus;
So, remember: every variable must have a value assigned to it before it can be used. As in your example, linus variable is non-nullable by default ,null-aware operator has nothing to do because it will assign value to linus if it is null.So, linus gets no value and thus it can't be used in the print function.
So to solve this, you can do this:
void main() {
int? linus; //marks linus as a variable that can have null value
linus ??= 100;
print(linus);
}
To know more about null safety
Upvotes: 1
Reputation: 5470
The Documentation is Non-Null Safety and you are trying in Null safety version Please check below code
void main() {
int? linus;
linus ??= 100;
print(linus);
}
Upvotes: 1