What Is State in Flutter?
State is any data that can change over time while your app is running. It could be a counter value, whether a switch is toggled, the items in a shopping cart, or the text inside a form field. When state changes, Flutter rebuilds the affected parts of the UI to reflect the new data.
// A simple example of state: a counter
// The number displayed on screen changes over time — that's state.
class CounterWidget extends StatefulWidget {
@override
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State {
int count = 0; // This is the state
@override
Widget build(BuildContext context) {
return Text('Count: $count'); // UI depends on state
}
}
Try it Yourself ->
Local State vs Global State
Local state belongs to a single widget and only affects that widget's UI. A toggle button that shows or hides a password field is local state — no other part of the app needs to know about it. Global state is data shared across multiple widgets or screens, like the current user's login status or items in a shopping cart.
// Local state — only this widget cares
class ToggleButton extends StatefulWidget {
@override
_ToggleButtonState createState() => _ToggleButtonState();
}
class _ToggleButtonState extends State {
bool isOn = false;
@override
Widget build(BuildContext context) {
return Switch(
value: isOn,
onChanged: (val) {
setState(() {
isOn = val;
});
},
);
}
}
// Global state — many widgets need this data
// This is where Provider, Riverpod, or Bloc come in later
Try it Yourself ->
When to Use Which Approach
Keep it simple: if only one widget needs the data, use local state with StatefulWidget and setState. If two or more widgets across different parts of the widget tree need the same data, you need a state management solution like Provider. Start with the simplest approach and only reach for more complex tools when you actually need them.
// Rule of thumb:
// - One widget cares? → setState
// - Multiple widgets care? → Provider or similar
// - Entire app cares (user auth, theme)? → Global state management
// Don't over-engineer early. Start with setState,
// and refactor when the pain of passing state around becomes real.
Try it Yourself ->