flutterdartnulldart-null-safetynull-safety

Why im getting this error Warning: Operand of null-aware operation '??' has type 'String' which excludes null. Dart Language


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


Solution

  • 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