Back to results for “Fundamentals”
Flutter › State Management with setState

What is setState, and how does calling it genuinely tell Flutter that a StatefulWidget's own internal data has actually changed and needs to be properly rebuilt?

Beginner

Answer

setState is a method genuinely available on a State object that, when called, tells Flutter that particular widget's own internal data has genuinely changed and that its own corresponding user interface therefore genuinely needs to be properly rebuilt to correctly reflect that particular change, and it accepts a callback function within which you actually genuinely perform your own required state mutation, and calling setState schedules a genuinely new call to that widget's own build method, correctly updating whatever part of the interface actually genuinely depends on that particular now updated data.
int _counter = 0;

void _incrementCounter() {
  setState(() {
    _counter++;
  });
}
Real-world example A simple counter app calls setState immediately after incrementing its own internal counter variable, correctly and explicitly notifying Flutter that the screen genuinely now needs to properly rebuild to accurately display that specific newly updated counter value.

Common follow-ups: What genuinely happens if you directly modify a State object's own internal variable without actually properly wrapping that particular change within a genuine setState call?;Is it genuinely required that the actual state mutation itself happens directly within the specific callback passed into setState?