Why the hell setState() sometimes does not work?

How to force a Widget to redraw in Flutter?

…and why Flutter tries to recycle Widgets’s State?

Jelena Lecic
4 min readAug 11, 2020

--

How many times have you called setState() and nothing on the screen has changed even though the internal State of the Widget has changed?
I know I have, many times :)

So, simple screen with a Text that displays current value that gets incremented each time user presses the button. This would be a no brainer if we were using a stateless Text Widget -> it would be rebuilt each time user clicks the button.

But, our implementation of the Text looks like this:

We take initial value from the Widget and store it locally in the State object during the initState() execution. initState() gets called only the first time when user presses the button, never again and this is why we do not see the changes on the screen. But why is this happening?

Well, this is actually how Flutter works - tries to keep Stateful Widget’s State.

Widgets are immutable, which means they need to be rebuilt on each setState() but their State is kept until, on the same position in the tree(Element tree), a new Widget appears with a different TYPE or a different KEY!

In our example, our Widget is at the same place as before(same Widget, so of-course the same type) and we did not use Keys, so from the point of the Element tree, nothing has changed and State gets…

--

--

Jelena Lecic

Flutter developer & consultant. You can find me at https://www.linkedin.com/in/jelena-lecic/ 👋👋👋