Flutter’s invisibility cloak — SetState()
As a newbie flutter developer, I got introduced to the idea of flutter through the Counter App. I am sure the first stepping stone was the same for all of the flutter developers out there.
Refreshing on the Counter App
Let’s have a look at the code for the counter app and try to analyse it.
It is a lot of code. Let us focus on what we need to analyse. The functional part of the code, the
_incrementCounter() function where the actual work of the counter app happens.
Here’s how it works:
- There’s one stateful field called
- We also have a
Textwidget that displays the value of
- Every time we want to update
_counter, we also have to wrap it in an anonymous function and pass it to
setState(). Otherwise, the framework doesn’t know what was updated.
While editing the code, I had a small slip up, and altered my function to the slightest bit.
I expected an error. Not a compile time or run-time error. I expected my app to go unresponsive. Clicking the button won’t do anything now. But I was wrong.
The app worked perfectly fine.
I started to question all my Flutter basics. Started a little investigation for myself. So it’s a voodoo doll a lot of people have already discovered and discussed and it wasn’t something I should have a ‘Eureka!’ moment about.
Let's take a peek behind the invisibility cloak
Too many terms! Let us simplify it down to understand what and how this piece of code exactly means. The function callback argument is triggered when
setState() is complete and the underlying method or widget is rendered. As it's a
async call, the callback argument is used for any action after rendering is done. All that
setState() does is call the provided callback and then the associated element gets scheduled for a new build.
What does all of this mean? Should we now convert all our
setState() calls to something like this?
Probably not. Even though there’s no difference, calling
setState()with an anonymous callback feels right.
At this point, the anonymous callback is an established convention and anything else just feels weird. So this is just a fun article you can have a laugh about!