15

When changing the state in a Flutter Widget, are there any differences between doing this

_variable1 = true;
variable2 = 'abc';
setState(() => {});

or this

setState(() => {
    _variable1 = true;
    variable2 = 'abc';
});

Almost all the examples in the docs use the last one, but I didn't notice any pratical differences. The variables are set and the state is updated in both cases, but I am wondering if there is a scenario that something doesn't work as expected if use one or another.

Ricardo Gonçalves
  • 4,344
  • 2
  • 20
  • 30
  • 2
    It doesn't make a difference but the 2nd makes the intention more clear. The state of `_variable1`band `variable2` was changed for the purpose of updating the view. – Günter Zöchbauer Feb 11 '19 at 19:26

4 Answers4

10

Already been posted here this question.

It's a convetion, it doesn't matter, but, it's good pratica to wrap all the changes inside the setState function. But the results will be the same in both cases.

Fellipe Malta
  • 3,160
  • 1
  • 7
  • 12
9

According to the flutter docs, it is stated that:

Generally it is recommended that the setState method only be used to wrap the actual changes to the state, not any computation that might be associated with the change.

Mainly I think that it is for readability purposes, i.e, you need to put in the body of setState what is changing in the new build of the widget, without mixing that with your computations as the first method in your question does.

Sami Kanafani
  • 14,244
  • 6
  • 45
  • 41
3

I've read somewhere that an empty setState is a "code smell", because the body of the callback should indicate the reason for the setState.

Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70
2

No , the result will be identical in both cases, I have used them both interchangeably in many widgets and the result was always the same.

Mazin Ibrahim
  • 7,433
  • 2
  • 33
  • 40