14

I am still a bit confused by the difference between these two

isBusy = false;
  setState(() {
});

and

setState(() {
  isBusy = true;
});

What is the difference between the two? I have read the API but unfortunately, I am still not clear on what difference does it make. I know setState calls the build method of the widget. The API states

Whenever you change the internal state of a State object, make the change in a function that you pass to setState: setState(() { _myState = newValue }); The provided callback is immediately called synchronously.

What exactly does this mean? can anyone give me a super simple example of when this would make a difference?

KetZoomer
  • 2,701
  • 3
  • 15
  • 43
MistyD
  • 16,373
  • 40
  • 138
  • 240

1 Answers1

15

There's no difference between using setState callback or not actually.

What's the point then ?

This is made voluntarily to prevent mistakes in handling asynchronous data.

By using the callback, there's a mistake you cannot do:

function() async {
  setState(() {});
  myState = await future;
}

This causes a problem because if your future doesn't finish synchronously, build method will be called with an invalid state.

By using the callback you are forced to do the following:

function() async {
  final value = await future;
  setState(() {
    myState = value;
  });
}

This time, it doesn't cause problems because the future is awaited before the setState.

Can't I make an async callback and stil have the issue?

No. Because setState method internally check that the callback does not return a future. And if it does, it will throw

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432