0

What is the difference between putting the value that need to be updated inside the setState vs outside?

setState(() {
  _counter++;
});

and

_counter++;
setState(() {});
Theuno de Bruin
  • 202
  • 2
  • 12
  • 2
    Does this answer your question? [Why does setState take a closure?](https://stackoverflow.com/questions/44379366/why-does-setstate-take-a-closure) – Christopher Moore Jul 27 '20 at 17:10

1 Answers1

0

assuming that you know what setState do, it is not the same but it do the same thing in your case you notify the framework that the internal state of this object has changed after changing the object internal state but if you use it as

setState(() {});
_counter++;

you might get unexpected result if your function takes a lot time the the setState wouldn't do anything

for example try this

setState(() {});
await Future.delayed(Duration(milliseconds: 500));
_counter++;

so it dependence on the function time and place(before or after setState). However it is better to put the value inside the setState to avoid unexpected behavior and it's the best practices for using setState as I know.

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
Mohammed Alfateh
  • 3,186
  • 1
  • 10
  • 24
  • someone just upload a video about your question here the link:https://www.youtube.com/watch?v=OnK679X9-0M&feature=push-u-sub&attr_tag=XFk3HWxLTusX870M%3A6 he explained better and it's just about 6 min :) – Mohammed Alfateh Jul 27 '20 at 19:55