How does Dart Compiler check for Null Safety?

Viewed 51
main(){

  String? string1;
  String? string2;
  String string3;

  if(string1!=null)
    string3=string1; // No Error
}

But

main(){

  String? string1;
  String? string2;
  String string3;

  if(string2!=null && string1==string2)
    string3=string1; // Error !
}

I am unable to understand the logic behind this. I think this has something to do with the dart compiler.

1 Answers

Even though you understand the process that string2 is not null and string2 == string1 (Hence string1 must not be null) the compiler just check that you validated the variable you want to use (and because you didn't check string1 != null it doesn't know the variable is not null). another example would be a class with a getter String?

class MyClass {
  final String _value = 'notEmpty';

  String? get value => _value;
}

You already know the getter returns _value and is of type String but the getter is always of type String? and you have to validate it each time

main(){
  final c = MyClass();
  String? string1 = c.value;
  String? string2;
  String string3;

  if(string2!=null && string1==string2)
    string3=string1; // Error because the compiler think at some point you could just send a String?!
  if (c.value != null) {
    string3 = c.value; // Error because the compiler think at some point you could just change c-value to a String?!
  }
}

For this cases you have a tool ! so even if the compiler doesn't understand it you already check it and told them that it's ok, that you're sure that value is of type String

if(string2!=null && string1==string2)
  string3 = string1!; // OK
if (c.value != null) {
  string3 = c.value!; // OK
}
Related