-1

The thing I am doing is calling setState() method and then updating the state after a delay of 5 seconds. Even then, i am seeing the State getting updated.

setState(() {
  print("callback");
});
sleep(const Duration(seconds: 5));
_randomNumber = Random().nextInt(100);
print("Number : $_randomNumber");

As you can see after the delay, _randomNumber is changing & I have set this _randomNumber value to a Text Widget. After 10 seconds, text is getting updated with the new _randomNumber. Then what is the use of calling setState(() {}) & wrapping the state changes only inside setState() ?

Sasank Sunkavalli
  • 3,864
  • 5
  • 31
  • 55
  • what do you want to achieve actually? why do you call `sleep` function at all? did you notice that this is a blocking function (try to set `seconds: 15` and interact with any components like buttons, text fields etc)? – pskink Oct 08 '20 at 04:01
  • @pskink this is not production ready code. I am just checking out how setState() method works, so trying out different things – Sasank Sunkavalli Oct 08 '20 at 04:17
  • use "await" with your sleep function make it future implementations "await sleep(const Duration(seconds: 5));" or "await Future.delayed(Duration(seconds:5))" – Anil Chauhan Oct 08 '20 at 04:48
  • so, what is not clear after you deleted blocking `sleep` function? – pskink Oct 08 '20 at 10:08
  • @pskink My doubts are cleared now. Thanks – Sasank Sunkavalli Oct 08 '20 at 10:14

1 Answers1

0

setState is the way to force an update immediately. It is your chance to control the timing. It is not the only way that the tree can get rebuild. Any number of other events can result in another call to your build function. But then you are not in control. It will get updated as a side-effect of something else happening.

nvoigt
  • 75,013
  • 26
  • 93
  • 142