Photo by Kelly Sikkema on Unsplash
In Flutter, stateless and stateful widgets are two fundamental types of widgets that define how a UI component behaves and interacts with the application state. It is important to differentiate between them as it is a concept used every time a developer tries to create a new widget
A StatelessWidget is immutable, meaning it cannot change its state after being created. It is designed for widgets whose configuration and appearance remain constant throughout their lifecycle.
Stateless widgets are typically used in Static text or images, icons and layout containers such as Row, Column or Containers. Example code given below:
class MyStatelessWidget extends StatelessWidget {
final String title;
MyStatelessWidget({required this.title});
@override
Widget build(BuildContext context) {
// Displays the title passed during creation
return Text(title);
}
}
In this example, MyStatelessWidget simply displays the title. You can't update the title after the widget is created.
A StatefulWidget is dynamic and can change during its lifecycle based on user interaction, data updates, or other events. It consists of two classes:
Stateful Widgets are typically used in Form inputs, Buttons with toggling states, Animations or timers or generally Widgets that respond to asynchronous data(Such as API calls).
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State {
int counter = 0;
void incrementCounter() {
setState(() {
counter++; // Updates the counter and refreshes the UI
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter: $counter'),
ElevatedButton(
onPressed: incrementCounter,
child: Text('Increment'),
),
],
);
}
}
In this example, pressing the button updates the counter state, which triggers a UI rebuild to reflect the new value. This is also the default code when building a new project in flutter.
Understanding the difference between Stateless and Stateless Widget is crucial as it affects the design of the whole application!