Skip to content

Null safety feedback: Null check required after checking a final field #1330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
vanlooverenkoen opened this issue Nov 22, 2020 · 2 comments
Closed
Labels
field-promotion Issues related to addressing the lack of field promotion

Comments

@vanlooverenkoen
Copy link

Why is this giving an error? The string is final so it will never be null.

image

void main() {
 
  final test = SomeClass(null);
  test.printPassword();
}

class SomeClass{
  final String? password;
  
  SomeClass(this.password);
  
  void printPassword(){
    if (password == null) {
      print('Password is null');
    }else{
      print(password + ' should never be null');
    }
  }
}
@vanlooverenkoen vanlooverenkoen changed the title Null check required after checking a final field Null safety feedback: Null check required after checking a final field Nov 22, 2020
@lrhn
Copy link
Member

lrhn commented Nov 22, 2020

Dart only ever promotes local variables. You can't know for sure that a virtual getter always returns the same value, even if it's a final field. A subclass can override the getter with something else, and that subclass might be declared in a completely different package.
Dart only promotes when it can prove that the value you test is also the same value that you are using later, based only on the signatures. It can only do that for local variables.

@lrhn lrhn transferred this issue from dart-lang/sdk Nov 22, 2020
@natebosch natebosch added the field-promotion Issues related to addressing the lack of field promotion label Feb 15, 2022
@natebosch
Copy link
Member

Closing since this is a duplicate and there is more in-depth conversation in other issues.
field-promotion Issues related to addressing the lack of field promotion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
field-promotion Issues related to addressing the lack of field promotion
Projects
None yet
Development

No branches or pull requests

3 participants