Flow analysis doesn't work when using setState

Issue

void f() {
  String string;
  setState(() {
    string = fooCondition ? 'foo' : 'bar';
  });
  
  string.toUpperCase(); // Error
}

If I remove the setState condition, the flow analysis work! I could put my setState below (blank setState(() {}) but that just reduce the readability of code. Is there any better way of doing it without making the string nullable and checking for nullability thereafter?

Solution

This is why you can also use late keyword in local scope.

late String string;

To answer your question:

void f() {
  late String string;
  setState(() {
    string = fooCondition ? 'foo' : 'bar';
  });

  string.toUpperCase(); // Works
}

Answered By – iDecode

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.