Skip to content

[NNBD] Analyser missing explicit null check for class fields #45265

Closed
@esDotDev

Description

@esDotDev
class Foo {
  String? label1;
  dynamic f() {
    String? label2;
    if (label1 != null) {
      return Text(label1); // compile error
    }
    if (label2 != null) {
      return Text(label2); // no compiler error
    }
  }
}

Why does the compiler complain here? Compiler should know that this is a final field? This pattern is used very often in flutter, where we will check a property of the widget to see if it's null.

final String label;

build(){
....
[
   if(label != null) Text(label), // Really don't want to have to use ! here, or put in a fallback that will never be used.
]
...
}

I think I understand this in general, because we can't be sure some subsequent function does not change a field. But, in this case its in the immediately following line. With something like if(value == null) return; how can there possibly be an issue? Additionally many times these fields are final so they actually can not be changed.

To work around this, we need to add local version of each field:

build(){
   String? label = widget.label;
   ...
   [
       if(label != null) Text(label), // works now
   ]
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions