0

In the following example:

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

What happens if I increase the counter before calling setState()? Like:

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

I really don't understand the difference and both versions work.

B Faley
  • 17,120
  • 43
  • 133
  • 223

2 Answers2

2

The functionality is basically the same. The only difference is Readability, calling _counter inside the setState callback makes it clear as to why you intend to rebuild a widget.

Calvin Gonsalves
  • 1,738
  • 11
  • 15
0

There is no difference between the placing counter++ inside and above setState. Whenever setState is called, it tells the entire widget to rebuild. However, it is recommended by the Flutter team to change your values inside setState instead of outside it to make it more readable and to prevent accidentally setting the values after setState is called. Here is an with multiple counters:

Bad: (Tells widget to rebuild but nothing has changed)

setState(() {});
_counter1++;
_counter2++;
_counter3++;

Not Recommended: (When you have other code besides changing the value, you would have to read the whole code to find out which variables are going to change)

_counter1++;
_counter2++;
_counter3++;
 setState(() {});

Good and Readable (Easy to know which variables are going to change even if you have other code like saving in SharedPreferences):

setState(() {
  _counter1++;
  _counter2++;
  _counter3++;
});
CoderUni
  • 5,474
  • 7
  • 26
  • 58
  • 1
    Although you could use setState to update the screen, you would have to do State Management in the future. setState is inefficient because you have to rebuild the whole screen even if you have only one widget that changed. Provider and Get_it also allows you to share a model between multiple screens without having to pass them around. https://flutter.dev/docs/development/data-and-backend/state-mgmt/options – CoderUni Jan 14 '21 at 01:33