Why Flutter does not immediately update variable inside setState?

Viewed 94

So I have code that basically like this:

int data;

void function() {
  print("First: $data");
  if (data == null) { 
    this.setState(() => data = 1); 
  }
  print("Second: $data");
}

The log will be:

First: null
Second: null

But if I do it like this:

int data;

void function() {
  print("First: $data");
  if (data == null) { 
    data = 1;
    this.setState(() => data = 1); 
  }
  print("Second: $data");
}

The result will be:

First: null
Second: 1

Why it's like this? I thought for a long time the calling of callback inside setState is synchronous? If it isn't then is it better if I do this instead:

int data;

void function() {
  print("First: $data");
  if (data == null) { 
    data = 1;
    this.setState(() {}); // nothing in the callback, set state is just marking UI needs to be updated
  }
  print("Second: $data");
}
1 Answers

check the implementation of setstate(), https://api.flutter.dev/flutter/widgets/State/setState.html, this does nothing with the data, it only validates that you have not returned a future.

The only important thing is that at the end it marks the widget to rebuild when the framework can do it with _element!.markNeedsBuild();

Related