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.
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.
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++;
});