Junior, State management, question 020
What is the purpose of setState()?
Question 020 · Junior
The answer
setState() tells the framework that the internal state of a State object has changed. It runs your callback synchronously (the callback must not be async) and schedules a build for that State object in the next frame. A rebuild is not the same as layout or repaint: a render object is laid out again or repainted only if its properties changed and it marked itself dirty.
The follow-up
You call setState three times in one tap handler. How many times does build run?
What a strong answer shows
Normally once, in the next frame. setState marks the State dirty and schedules a frame, so calls made before that frame are batched into one rebuild. A strong answer adds the failure case: calling setState after dispose throws, so cancel the asynchronous work or check mounted first.
