What is Stateful Widget in Flutter: Explanation and Example
StatefulWidget in Flutter is a widget that can change its appearance or behavior during runtime by holding mutable state. It rebuilds its UI when its state changes, allowing dynamic and interactive apps.How It Works
A StatefulWidget works like a container that holds information that can change over time, called state. Imagine a light switch that can be turned on or off; the switch's position is the state. When the state changes, the widget updates its look to match the new state.
Flutter separates the widget itself from its state. The widget is like a blueprint, and the state is the current condition. When you change the state, Flutter calls a special method to rebuild the widget with the new information, so the screen updates smoothly.
Example
This example shows a button that counts how many times it is pressed. The number updates on the screen each time you tap the button, demonstrating how StatefulWidget holds and updates state.
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: CounterWidget(), ); } } class CounterWidget extends StatefulWidget { const CounterWidget({super.key}); @override State<CounterWidget> createState() => _CounterWidgetState(); } class _CounterWidgetState extends State<CounterWidget> { int _count = 0; void _increment() { setState(() { _count++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Stateful Widget Example')), body: Center( child: Text('Button pressed: $_count times', style: const TextStyle(fontSize: 24)), ), floatingActionButton: FloatingActionButton( onPressed: _increment, child: const Icon(Icons.add), ), ); } }
When to Use
Use a StatefulWidget when your UI needs to change dynamically based on user actions, data updates, or time. For example:
- Buttons that update counters or toggle states
- Forms where users enter and edit data
- Animations that change over time
- Loading indicators that appear and disappear
If your widget never changes after it appears, use a StatelessWidget instead.
Key Points
- StatefulWidget holds mutable state that can change during the widget's lifetime.
- State changes trigger UI rebuilds to reflect updates.
- The widget class is immutable; the mutable state is kept in a separate
Stateclass. - Use
setState()to notify Flutter to rebuild the widget with new state.