0

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 :)

Yamix.co
  • 3
  • 1
  • 3

3 Answers3

0

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.

Ares
  • 2,504
  • 19
  • 19
0

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

Dani3le_
  • 1,257
  • 1
  • 13
  • 22
0

Dart, by default, will assume any variable you've declared can never be null. You won't be able to assign null to a variable, and at runtime it will throw an error. It will also complain if you try to treat a non-nullable variable like it could be null, which is what you're doing with '??'.

You can use the ? after a variable's type to tell Dart that your variable will accept null values. ?? allows us to handle null values without writing extra lines of code

In short, x = y ?? z can be described as

If the left operand (y) is null, then assign the right operand (z) ie.

void example(String? myString) {
  String? y = myString;
  String z = 'spam';

  var x = y ?? z;
  print(x);
}

void main() {
  example('hello!');
  example(null);
}

// Output:
// hello!
// spam

Notice that I've added '?' after 'String' on the 2nd line, letting Dart know that 'y' could be null. This prevents me getting an error later in the code where I try to use a null-aware operator (??) to assign it to 'x'.

I hope this helped give you some background beyond just resolving your issue! :)

Short medium article on Null-aware operators in Dart

TDuff
  • 78
  • 7
  • Yes this one was helpful, i see that name is allowed to be null if there is no input give it GuestUser, Thanks for the help i really appreciate it <3 . – Yamix.co Feb 11 '22 at 22:45
  • the same idea that I got from the course but with the wrong code, I think the course is 3 years old should I just change it or follow the same course & dart doc. – Yamix.co Feb 11 '22 at 22:49