Home > Software engineering >  Why im getting this error Warning: Operand of null-aware operation '??' has type 'Str
Why im getting this error Warning: Operand of null-aware operation '??' has type 'Str

Time:02-11

so i was learning about SWITCH and CASE Statements in dart language, in the course he explains the code but he don't get an error while i get one.

the error i get : Warning: Operand of null-aware operation '??' has type 'String' which excludes null. String ``userName = name ?? "Guest User";

My Code is

void learnCondExpr() {
 String name = 'Yamix';
    
 String userName = name ?? "Guest User";
 print(userName);
}

can i get some help please :)

CodePudding user response:

So ?? operation must be put after a nullable variable. But in your code name variable is String, not nullable. So ?? "Guest User" is always ignored. The warning is saying about that - this code is useless.

P.S. If you fix code to String? name = 'Yamix';, the warning will go away.

CodePudding user response:

The probem is that name is not-nullable String. You can declare it as a nullable type by adding a ?.

Like this:

String? name = 'Yamix';

Keep in mind that even if your string is nullable but you assign a value to it, that's going to be constant, and that's the reason why you may be getting a warning when checking it for null:

The left operand can't be null, so the right operand is never executed. Try removing the operator and the right operand

  • Related