Skip to content

Assignment expressions in if-statements don't correctly promote nullable variables #3658

@skylon07

Description

@skylon07

This program errors:

void main() {
  String? getString() => "asdf";

  String? someString;
  if ((someString = getString()) != null) {
    // errors:
    // "The property 'isNotEmpty' can't be unconditionally accessed because the receiver can be 'null'."
    print(someString.isNotEmpty);
  }
}

This one does not:

void main() {
  String? getString() => "asdf";

  String? someString;
  someString = getString();
  if (someString != null) {
    // does not error
    print(someString.isNotEmpty);
  }
}

I feel like the first program shouldn't error... Doesn't it guarantee that someString is not nullable just as much as the second program does? I might be wrong here -- I don't usually use assignment syntax in if-statements like this. (If you're curious, I'm using this syntax to store the results of a chain of nullable RegExp matches, which looks neater than having several assignments put between unchained if-statements.)

Infos

  • Dart 3.3.1 (stable) (Wed Mar 6 13:09:19 2024 +0000) on "macos_arm64"
  • on macos / Version 14.0 (Build 23A344)
  • locale is en-US

Metadata

Metadata

Assignees

No one assigned

    Labels

    flow-analysisDiscussions about possible future improvements to flow analysisrequestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions